Pierrew
Pierrew

Reputation: 482

Converting Bitmap to ByteArray and back to Bitmap not working

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

Upvotes: 0

Views: 789

Answers (1)

Vladyslav Matviienko
Vladyslav Matviienko

Reputation: 10871

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

Upvotes: 1

Related Questions