Bishwa
Bishwa

Reputation: 1

How to convert image to byte array and convert back byte array to image

I am trying to convert an image to byte array and converting back byte array to image in Android Emulator. First part is working fine but the second part is not creating the image file in Android emulator.

Please suggest me if there is any correction in my second part of the code.

Following is my code.

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; 
}

Upvotes: 0

Views: 5187

Answers (1)

Chris White
Chris White

Reputation: 30089

your call to BitmapFactory.decodeByteArray(..) - this method returns a Bitmap object, but you're not assigning it to anything. You also need to change the call to pass in the actual length of byte_img_data, rather then 200.

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

However, whether decodeByteArray(..) can handle compressed streams, i don't know

Upvotes: 1

Related Questions