java - 如何将图像转换为字节数组以及将字节数组转换回图像

标签 java android android-emulator bitmap arrays

我正在尝试将图像转换为字节数组,然后在 Android 模拟器中将字节数组转换回图像。 第一部分工作正常,但第二部分未在 Android 模拟器中创建图像文件。

如果我的代码的第二部分有任何更正,请建议我。

以下是我的代码。

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(..) 的调用 - 此方法返回一个 Bitmap 对象,但您没有将其分配给任何对象。您还需要更改调用以传入 byte_img_data 的实际长度,而不是 200。

Bitmap bitmap2 = BitmapFactory.decodeByteArray(byte_img_data, 0, byte_img_data.length);

但是,decodeByteArray(..)是否可以处理压缩流,我不知道

关于java - 如何将图像转换为字节数组以及将字节数组转换回图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9821964/

相关文章:

android - NumberFormatter 函数在德语语言环境下无法正常工作

java - com.sun.jersey.api.view.Viewable无法解析,它是从required.class间接引用的

java - 如果写入的值始终相同,则延迟初始化引用是否是线程安全的?

Java CodingBat 逻辑茶会?

android - 开设 AdMob 帐户

未在 Release模式下调用 Android MY_PACKAGE_REPLACED

android - 带有 CheckBox 的 ListView 的奇怪行为

android-emulator - 模拟器中没有日历

Java - table - 改变表格格式

android - 在android中获取Udid