我想将bmp图像转换为android中的字节数组,使用mobiwire Device打印它, 我正在尝试使用此功能,但打印机输出为空白图像
这个功能:
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
答案 0 :(得分:0)
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();
}
}
答案 1 :(得分:0)
这是最佳且简单的解决方案,可将图像编码和解码为字节数组。
用于将位图图像编码为字节数组使用。
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;
}
}