专栏首页恩蓝脚本Android 实现图片转二进制流及二进制转字符串

Android 实现图片转二进制流及二进制转字符串

我就废话不多说了,还是直接看代码吧

public static byte[] readStream(String imagepath) throws Exception {
  FileInputStream fs = new FileInputStream(imagepath);
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while (-1 != (len = fs.read(buffer))) {
    outStream.write(buffer, 0, len);
  }
  outStream.close();
  fs.close();
  return outStream.toByteArray();
}

// 二进制转字符串
public static String byte2hex(byte[] b)
{
  StringBuffer sb = new StringBuffer();
  String tmp = "";
  for (int i = 0; i < b.length; i++) {
    tmp = Integer.toHexString(b[i] & 0XFF);
    if (tmp.length() == 1){
      sb.append("0" + tmp);
    }else{
      sb.append(tmp);
    }

  }
  return sb.toString();
}

补充知识:图片(bitmap)转化为byte[],并上传到服务器

压缩为3:1bitmap

/**
   * 压缩bitmap
   *
   * @param bitmap
   * @return
   */
  private Bitmap compressBitmap(Bitmap bitmap) {
    // 创建操作图片用的matrix对象
    Matrix matrix = new Matrix();
    matrix.postScale((float) 300 / bitmap.getWidth(),
        (float) 100 / bitmap.getHeight());
 
    Log.e("", "bitmap_width" + bitmap.getWidth());
    Log.e("", "bitmap_height" + bitmap.getHeight());
    Bitmap compressBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    return compressBitmap;
  }

上传压缩后的bitmap

private void eleSignature() {
WritePadDialog writeTabletDialog = new WritePadDialog(
this, new DialogListener() {
public void refreshActivity(Object object) {
Bitmap mSignBitmap = (Bitmap) object;
mSignBitmap = compressBitmap(mSignBitmap);
//        Bitmap newsrcImage = mSignBitmap.copy(Bitmap.Config.RGB_565, true);
saveBmp(mSignBitmap);
Log.e("", "after bitmap_width:" + mSignBitmap.getWidth());
Log.e("", "after bitmap_height:" + mSignBitmap.getHeight());
File file = new File(file_name);
Log.e("Jeny", "file.exists():" + file.exists());
if (!file.exists()) {
return;
}
byte[] eleSignatureData = null;
try {
eleSignatureData = InputStreamTOByte();
} catch (IOException e) {
}
Log.e("Jeny", "eleSignatureData:" + eleSignatureData.length);
if (eleSignatureData == null) {
return;
}
//        byte[] eleSignatureData = InputStreamTOByte();
//        byte[] eleSignatureData = Bitmap2Bytes(newsrcImage);
mController.startSavingElecSignatureDataOfSDPay(SalesCollectActivity.this, voucherNo, eleSignatureData);
mSignBitmap.recycle();
}
}
);
writeTabletDialog.setCanceledOnTouchOutside(false);
writeTabletDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
} else {
return false; //默认返回 false
}
}
});
writeTabletDialog.show();
}
/**
* 将InputStream转换成byte数组
* <p/ 
* InputStream
*
* @return byte[]
* @throws IOException
*/
@SuppressWarnings("resource")
public byte[] InputStreamTOByte() throws IOException {
File file = new File(file_name);
if (!file.exists()) {
return null;
}
FileInputStream is = new FileInputStream(file_name);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1)
outStream.write(data, 0, count);
// data = null;
byte[] alldata = outStream.toByteArray();
/**top = new byte[62];
for (int i = 0; i < 62; i++)
{
top[i] = alldata[i];
}
writefile(top_name, top);
*/
//    byte[] other = new byte[alldata.length - 62];
//    for (int i = 0; i < (alldata.length - 62); i++)
//    {
//      other[i] = alldata[i + 62];
//    }
/*
* String b =
* Environment.getExternalStorageDirectory().getPath()+"/other.txt";
* writefile(b, other);
*/
return alldata;
}
/**
* @param bitmap 图片以bmp格式存储的方法
*/
private void saveBmp(Bitmap bitmap) {
if (bitmap == null)
return;
// 位图大小
int nBmpWidth = bitmap.getWidth();
int nBmpHeight = bitmap.getHeight();
int DataSizePerLine = 40;
// 图像数据大小
int bufferSize = nBmpHeight * DataSizePerLine;
try {
// 存储文件名
File file = new File(file_name);
Log.i("SurFace", "filename:" + file_name);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileos = new FileOutputStream(file_name);
// bmp文件头
int bfType = 0x4d42;
long bfSize = 14 + 40 + 8 + bufferSize;
int bfReserved1 = 0;
int bfReserved2 = 0;
long bfOffBits = 14 + 40 + 8;
// 保存bmp文件头
writeWord(fileos, bfType);
writeDword(fileos, bfSize);
writeWord(fileos, bfReserved1);
writeWord(fileos, bfReserved2);
writeDword(fileos, bfOffBits);
// bmp信息头
long biSize = 40L;
long biWidth = nBmpWidth;
long biHeight = nBmpHeight;
int biPlanes = 1;
int biBitCount = 1;
long biCompression = 0L;
long biSizeImage = 0L;
long biXpelsPerMeter = 0L;
long biYPelsPerMeter = 0L;
long biClrUsed = 0L;
long biClrImportant = 0L;
// 保存bmp信息头
writeDword(fileos, biSize);
writeLong(fileos, biWidth);
writeLong(fileos, biHeight);
writeWord(fileos, biPlanes);
writeWord(fileos, biBitCount);
writeDword(fileos, biCompression);
writeDword(fileos, biSizeImage);
writeLong(fileos, biXpelsPerMeter);
writeLong(fileos, biYPelsPerMeter);
writeDword(fileos, biClrUsed);
writeDword(fileos, biClrImportant);
// 调色板
byte[] c = new byte[4];
c[0] = 0;
c[1] = 0;
c[2] = 0;
c[3] = 0;
fileos.write(c);
byte[] w = new byte[4];
w[0] = (byte) 255;
w[1] = (byte) 255;
w[2] = (byte) 255;
w[3] = 0;
fileos.write(w);
int wWidth = DataSizePerLine;
// 像素扫描
byte bmpData[] = new byte[bufferSize];
for (int ibuf = 0; ibuf < bufferSize; ibuf++)
bmpData[ibuf] = (byte) 0xff;
int iByte = 0;
int iCount = 0;
byte bPix = 0;
for (int nCol = nBmpHeight - 1, nRealCol = nBmpHeight; nCol   0; nCol--, nRealCol--) {
wWidth = DataSizePerLine;
iCount = 0;
iByte = 0;
for (int wRow = 0; wRow < nBmpWidth; wRow++) {
int clr = bitmap.getPixel(wRow, nCol);
int r = (clr | 0xff00ffff)    16 & 0x00ff;
int g = Color.green(clr);
int b = Color.blue(clr);
// byte a = (byte) Color.blue(clr);
// byte b = (byte) Color.green(clr);
// byte d = (byte) Color.red(clr);
// System.out.println("r:"+r);
if (r != 255 || g != 255 || b != 255)// 黑色
{
// bPix = (byte)(bPix & (0x7f  iByte |
// 0x7f<<(8-iByte)));
bPix = (byte) (bPix & ~(byte) Math.pow(2, iByte));
// System.out.println( " 黑色 " + bPix );
} else {
// bPix = (byte)(bPix & (0xff  iByte |
// 0xff<<(8-iByte)));
bPix = (byte) (bPix | (byte) Math.pow(2, iByte));
// System.out.println( " 白色 " + bPix);
}
if (iCount != 0 && iCount % 8 == 0) {
bmpData[nRealCol * wWidth - wRow / 8] = bPix;
iByte = 0;
} else {
iByte++;
}
iCount++;
/*
* //if(a==b && b==d && a 0) if (nRealCol%2 == 0) { //为白色
* bmpData[nRealCol * wWidth] = (byte)255; }else{ //为黑色
* bmpData[nRealCol * wWidth] = 0; }
*/
// Arrays.fill(x, value);
/*
* bmpData[nRealCol * wWidth + wByteIdex] = (byte) Color .b;
* bmpData[nRealCol * wWidth + wByteIdex + 1] = (byte) Color
* .green(clr); bmpData[nRealCol * wWidth + wByteIdex + 2] =
* (byte) Color .red(clr);
*/
}
}
// System.out.println( " iCount= " + iCount);
/*
* byte[] writeByte = new byte[bmpData.length]; for(int
* i=0;i<writeByte.length;i++){ writeByte[i] =
* bmpData[bmpData.length-i-1]; }
*/
fileos.write(bmpData);
fileos.flush();
fileos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void writeWord(FileOutputStream stream, int value)
throws IOException {
byte[] b = new byte[2];
b[0] = (byte) (value & 0xff);
b[1] = (byte) (value    8 & 0xff);
stream.write(b);
}
protected void writeDword(FileOutputStream stream, long value)
throws IOException {
byte[] b = new byte[4];
b[0] = (byte) (value & 0xff);
b[1] = (byte) (value    8 & 0xff);
b[2] = (byte) (value    16 & 0xff);
b[3] = (byte) (value    24 & 0xff);
stream.write(b);
}
protected void writeLong(FileOutputStream stream, long value)
throws IOException {
byte[] b = new byte[4];
b[0] = (byte) (value & 0xff);
b[1] = (byte) (value    8 & 0xff);
b[2] = (byte) (value    16 & 0xff);
b[3] = (byte) (value    24 & 0xff);
stream.write(b);
}
/**
* 压缩bitmap
*
* @param bitmap
* @return
*/
private Bitmap compressBitmap(Bitmap bitmap) {
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
matrix.postScale((float) 300 / bitmap.getWidth(),
(float) 100 / bitmap.getHeight());
Log.e("", "bitmap_width" + bitmap.getWidth());
Log.e("", "bitmap_height" + bitmap.getHeight());
Bitmap compressBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return compressBitmap;
}

以上这篇Android 实现图片转二进制流及二进制转字符串就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Android使用RSA加密和解密的示例代码

    1.data是要加密的数据,如果是字符串则getBytes。publicKey是公钥,privateKey是私钥。自定义密钥对测试

    砸漏
  • Android利用LitePal操作数据库存取图片

    Android数据库中存取图片通常使用两种方式,一种是保存图片所在路径,二是将图片以二进制的形式存储(sqlite3支持BLOB数据类型)。对于两种方法的使用,...

    砸漏
  • Linux动态链接库的使用

    动态链接库与普通的程序相比而言,没有main函数,是一系列函数的实现。通过shared和fPIC编译参数生产so动态链接库文件。程序在调用库函数时,只需要连接上...

    砸漏
  • C# 热敏打印机 Socket 网络链接 打印 图片 (二)

    跟着阿笨一起玩NET
  • pdf转html插件~~~pdf2htmlEX安装,配置及使用

    https://github.com/coolwanglu/pdf2htmlEX/wiki

    lin_zone
  • 框架源码调试实战之easypoi异常解决方案精讲

    最近有个同事遇到了个棘手的问题,easypoi导出文件出了bug,却不知道是怎么回事,无从下手,无可奈何,由于事态紧急,只能火急火急的求助于我。我问他...

    Java深度编程
  • Python语言实现Dijkstra算法

    Dijkstra算法是由荷兰计算机科学家狄克斯特拉(Dijkstra)于1959 年提出的,因此又叫狄克斯特拉算法。是从一个顶点到其余各顶点的最短路径算法,解决...

    week
  • Java习惯用法总结

    在Java编程中,有些知识 并不能仅通过语言规范或者标准API文档就能学到的。在本文中,我会尽量收集一些最常用的习惯用法,特别是很难猜到的用法。(Joshua ...

    Java后端工程师
  • 观点 | Waymo自动驾驶车每天行驶25000英里,但CEO却告诉我们距离成功还远

    纽约 3 月 27 日,Waymo 首席执行官约翰·科拉菲克(John Krafcik)站在一辆捷豹 I-Pace 旁。自动驾驶汽车先驱 Waymo 将从捷豹路...

    机器之心
  • 前端-小程序构建骨架屏的探索

    一般情况下,在首屏数据未拿到之前,为了提升用户的体验,会在页面上展示一个loading的图层,类似下面这个:

    grain先森

扫码关注云+社区

领取腾讯云代金券