转换bmp图像为Android中的字节数组获取空白图像

问题描述:

我想要将bmp图像转换为android中的字节数组以使用mobiwire设备进行打印Device, 我试图使用此功能执行此操作,但打印机输出为空白图像转换bmp图像为Android中的字节数组获取空白图像

此功能:

public static byte[] decodeBitmap(Bitmap bmp){ 
     int bmpWidth = bmp.getWidth(); 
     int bmpHeight = bmp.getHeight(); 

     List<String> list = new ArrayList<String>(); //binaryString list 
     StringBuffer sb; 


     int bitLen = bmpWidth/8; 
     int zeroCount = bmpWidth % 8; 

     String zeroStr = ""; 
     if (zeroCount > 0) { 
      bitLen = bmpWidth/8 + 1; 
      for (int i = 0; i < (8 - zeroCount); i++) { 
       zeroStr = zeroStr + "0"; 
      } 
     } 

     for (int i = 0; i < bmpHeight; i++) { 
      sb = new StringBuffer(); 
      for (int j = 0; j < bmpWidth; j++) { 
       int color = bmp.getPixel(j, i); 

       int r = (color >> 16) & 0xff; 
       int g = (color >> 8) & 0xff; 
       int b = color & 0xff; 

       // if color close to white,bit='0', else bit='1' 
       if (r > 160 && g > 160 && b > 160) 
        sb.append("0"); 
       else 
        sb.append("1"); 
      } 
      if (zeroCount > 0) { 
       sb.append(zeroStr); 
      } 
      list.add(sb.toString()); 
     } 

     return hexList2Byte(commandList); 
    } 

我在我的测试使用Mobiwire装置2G

public static void convertToByteArray(BufferedImage image, String type) { 
    String imageString = null; 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

    try { 
     ImageIO.write(image, type, bos); 
     byte[] imageBytes = bos.toByteArray(); 
     bos.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

图像首先编码为base64字符串使用上述方法,然后使用以下方法的base64编码为字节阵列..... –

这是最好的和简单的解决方案编码和解码图像字节数组。

用于将位图图像编码为字节数组的使用。

public String encodeTobase64(Bitmap image) { 
     Bitmap immage = getResizedBitmap(image, 100, 80); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     immage.compress(Bitmap.CompressFormat.PNG, 100, baos); 
     byte[] b = baos.toByteArray(); 
     String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT); 
     Log.d("Image Log:", imageEncoded); 
     return imageEncoded; 
    } 

要取回图像使用

public Bitmap decodeBase64(String input) { 
    try { 
     byte[] decodedByte = Base64.decode(input, Base64.DEFAULT); 
     return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } 
}