SoFunction
Updated on 2025-03-11

Android implements image to binary stream and binary to string

I won't say much nonsense, just look at the code

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 = (buffer))) {
    (buffer, 0, len);
  }
  ();
  ();
  return ();
}

// Binary to stringpublic static String byte2hex(byte[] b)
{
  StringBuffer sb = new StringBuffer();
  String tmp = "";
  for (int i = 0; i < ; i++) {
    tmp = (b[i] & 0XFF);
    if (() == 1){
      ("0" + tmp);
    }else{
      (tmp);
    }

  }
  return ();
}

Supplementary knowledge:The image (bitmap) is converted into byte[] and uploaded to the server

Compressed to 3:1 bitmap

/**
    * Compress bitmap
    *
    * @param bitmap
    * @return
    */
  private Bitmap compressBitmap(Bitmap bitmap) {
    // Create matrix object for operation pictures    Matrix matrix = new Matrix();
    ((float) 300 / (),
        (float) 100 / ());
 
    ("", "bitmap_width" + ());
    ("", "bitmap_height" + ());
    Bitmap compressBitmap = (bitmap, 0, 0,
        (), (), matrix, true);
    return compressBitmap;
  }

Upload compressed 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 = (.RGB_565, true);
        saveBmp(mSignBitmap);
        ("", "after bitmap_width:" + ());
        ("", "after bitmap_height:" + ());
        File file = new File(file_name);
        ("Jeny", "():" + ());
        if (!()) {
          return;
        }
        byte[] eleSignatureData = null;
        try {
          eleSignatureData = InputStreamTOByte();
        } catch (IOException e) {
 
        }
        ("Jeny", "eleSignatureData:" + );
        if (eleSignatureData == null) {
          return;
        }
 
//        byte[] eleSignatureData = InputStreamTOByte();
//        byte[] eleSignatureData = Bitmap2Bytes(newsrcImage);
        (, voucherNo, eleSignatureData);
        ();
      }
 
    }
    );
    (false);
    (new () {
      @Override
      public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          return true;
        } else {
          return false; //Return false by default        }
      }
    });
    ();
  }
 
  /**
    * Convert InputStream to byte array
    * <p/>
    * InputStream
    *
    * @return byte[]
    * @throws IOException
    */
  @SuppressWarnings("resource")
  public byte[] InputStreamTOByte() throws IOException {
    File file = new File(file_name);
    if (!()) {
      return null;
    }
    FileInputStream is = new FileInputStream(file_name);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] data = new byte[BUFFER_SIZE];
    int count = -1;
    while ((count = (data, 0, BUFFER_SIZE)) != -1)
      (data, 0, count);
    // data = null;
    byte[] alldata = ();
 
    /**top = new byte[62];
     for (int i = 0; i &lt; 62; i++)
     {
     top[i] = alldata[i];
     }
     writefile(top_name, top);
     */
//    byte[] other = new byte[ - 62];
//    for (int i = 0; i &lt; ( - 62); i++)
//    {
//      other[i] = alldata[i + 62];
//    }
    /*
     * String b =
		 * ().getPath()+"/";
		 * writefile(b, other);
		 */
    return alldata;
  }
  /**
    * @param bitmap How to store images in bmp format
    */
  private void saveBmp(Bitmap bitmap) {
    if (bitmap == null)
      return;
    // Bitmap size    int nBmpWidth = ();
    int nBmpHeight = ();
    int DataSizePerLine = 40;
    // Image data size    int bufferSize = nBmpHeight * DataSizePerLine;
    try {
      //Storage file name      File file = new File(file_name);
      ("SurFace", "filename:" + file_name);
      if (!()) {
        ();
      }
      FileOutputStream fileos = new FileOutputStream(file_name);
      // bmp file header      int bfType = 0x4d42;
      long bfSize = 14 + 40 + 8 + bufferSize;
      int bfReserved1 = 0;
      int bfReserved2 = 0;
      long bfOffBits = 14 + 40 + 8;
      // Save the bmp file header      writeWord(fileos, bfType);
      writeDword(fileos, bfSize);
      writeWord(fileos, bfReserved1);
      writeWord(fileos, bfReserved2);
      writeDword(fileos, bfOffBits);
      // bmp information header      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;
      // Save the bmp information header      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);
      // Palette      byte[] c = new byte[4];
      c[0] = 0;
      c[1] = 0;
      c[2] = 0;
      c[3] = 0;
      (c);
      byte[] w = new byte[4];
      w[0] = (byte) 255;
      w[1] = (byte) 255;
      w[2] = (byte) 255;
      w[3] = 0;
      (w);
      int wWidth = DataSizePerLine;
      // Pixel scan      byte bmpData[] = new byte[bufferSize];
      for (int ibuf = 0; ibuf &lt; bufferSize; ibuf++)
        bmpData[ibuf] = (byte) 0xff;
      int iByte = 0;
      int iCount = 0;
      byte bPix = 0;
      for (int nCol = nBmpHeight - 1, nRealCol = nBmpHeight; nCol &gt; 0; nCol--, nRealCol--) {
        wWidth = DataSizePerLine;
        iCount = 0;
        iByte = 0;
        for (int wRow = 0; wRow &lt; nBmpWidth; wRow++) {
          int clr = (wRow, nCol);
 
          int r = (clr | 0xff00ffff) &gt;&gt; 16 &amp; 0x00ff;
          int g = (clr);
          int b = (clr);
          // byte a = (byte) (clr);
          // byte b = (byte) (clr);
          // byte d = (byte) (clr);
          // ("r:"+r);
          if (r != 255 || g != 255 || b != 255)// black          {
            // bPix = (byte)(bPix &amp; (0x7f&gt;&gt;iByte |
            // 0x7f&lt;&lt;(8-iByte)));
            bPix = (byte) (bPix &amp; ~(byte) (2, iByte));
            // ( "Black" + bPix);          } else {
            // bPix = (byte)(bPix &amp; (0xff&gt;&gt;iByte |
            // 0xff&lt;&lt;(8-iByte)));
            bPix = (byte) (bPix | (byte) (2, iByte));
            // ( "White" + bPix);          }
          if (iCount != 0 &amp;&amp; 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) { //It is white
					  * bmpData[nRealCol * wWidth] = (byte)255; }else{ // is black
					  * bmpData[nRealCol * wWidth] = 0; }
					  */
          // (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);
					 */
        }
      }
      // ( " iCount= " + iCount);
      /*
       * byte[] writeByte = new byte[]; for(int
			 * i=0;i&lt;;i++){ writeByte[i] =
			 * bmpData[-i-1]; }
			 */
      (bmpData);
      ();
      ();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      ();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      ();
    }
  }
  protected void writeWord(FileOutputStream stream, int value)
      throws IOException {
    byte[] b = new byte[2];
    b[0] = (byte) (value &amp; 0xff);
    b[1] = (byte) (value &gt;&gt; 8 &amp; 0xff);
 
    (b);
  }
 
  protected void writeDword(FileOutputStream stream, long value)
      throws IOException {
    byte[] b = new byte[4];
    b[0] = (byte) (value &amp; 0xff);
    b[1] = (byte) (value &gt;&gt; 8 &amp; 0xff);
    b[2] = (byte) (value &gt;&gt; 16 &amp; 0xff);
    b[3] = (byte) (value &gt;&gt; 24 &amp; 0xff);
 
    (b);
  }
 
  protected void writeLong(FileOutputStream stream, long value)
      throws IOException {
    byte[] b = new byte[4];
    b[0] = (byte) (value &amp; 0xff);
    b[1] = (byte) (value &gt;&gt; 8 &amp; 0xff);
    b[2] = (byte) (value &gt;&gt; 16 &amp; 0xff);
    b[3] = (byte) (value &gt;&gt; 24 &amp; 0xff);
 
    (b);
  }
 
  /**
    * Compress bitmap
    *
    * @param bitmap
    * @return
    */
  private Bitmap compressBitmap(Bitmap bitmap) {
    // Create matrix object for operation pictures    Matrix matrix = new Matrix();
    ((float) 300 / (),
        (float) 100 / ());
 
    ("", "bitmap_width" + ());
    ("", "bitmap_height" + ());
    Bitmap compressBitmap = (bitmap, 0, 0,
        (), (), matrix, true);
    return compressBitmap;
  }

The above article on Android's image to binary stream and binary to string are all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.