Java 如何将图像转换为字节数组并将字节数组转换回图像
我正在尝试在Android Emulator中将图像转换为字节数组,并将字节数组转换回图像。 第一部分工作正常,但第二部分不是在Android emulator中创建图像文件 如果我的代码第二部分有任何修改,请告诉我 下面是我的代码Java 如何将图像转换为字节数组并将字节数组转换回图像,java,android,android-emulator,bitmap,bytearray,Java,Android,Android Emulator,Bitmap,Bytearray,我正在尝试在Android Emulator中将图像转换为字节数组,并将字节数组转换回图像。 第一部分工作正常,但第二部分不是在Android emulator中创建图像文件 如果我的代码第二部分有任何修改,请告诉我 下面是我的代码 public String GetQRCode() throws FileNotFoundException, IOException { /* * In this function the first part shows how to conv
public String GetQRCode() throws FileNotFoundException, IOException {
/*
* In this function the first part shows how to convert an image file to
* byte array. The second part of the code shows how to change byte array
* back to an image.
*/
Bitmap bitmap = BitmapFactory.decodeFile("sdcard/Download/QR.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] byte_img_data = baos.toByteArray();
byte[] buf = new byte[200];
// Second Part: Convert byte array back to an image
Bitmap bitmap2 = BitmapFactory.decodeByteArray(byte_img_data, 0, 200);
ByteArrayOutputStream img= new ByteArrayOutputStream();
Bitmap imageFile= BitmapFactory.decodeFile("sdcard/Download/QR3.jpg");
String abc = buf.toString();
return abc;
}
调用
BitmapFactory.decodeByteArray(..)
-此方法返回位图对象,但不将其分配给任何对象。您还需要将调用更改为传入的实际长度为byte\u img\u data
,而不是200
Bitmap bitmap2 = BitmapFactory.decodeByteArray(byte_img_data, 0, byte_img_data.length);
然而,
decodeByteArray(…)
是否可以处理压缩流,我不知道有没有理由相信这在模拟器中的工作(或失败)与在手机或平板电脑中的工作(或失败)不同?如果不是,这与模拟器无关。你能试试@Chris White answer吗?