Converting Bitmap to ByteArray and back to Bitmap not working

785 views Asked by At

I tried to convert Bitmap to byteBuffer and then convert it back to Bitmap with the following code. No error occurs but the ImageView is unable to display anything on the screen. The image is 640 X 480 RGB jpeg.

    Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString()+"/tower.jpg");

    ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
    bitmap.copyPixelsToBuffer(byteBuffer);
    byte[] byteArray = byteBuffer.array();

    Bitmap final_bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    ((ImageView) findViewById(R.id.imageView)).setImageBitmap(final_bitmap);
1

There are 1 answers

3
Vladyslav Matviienko On

Try converting bitmap to byte array this way:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

And byteArray to bitmap as you do

Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);