How to convert byte array to Bitmap

Vasu picture Vasu · Oct 1, 2011 · Viewed 206.5k times · Source

I want to store image in SQLite DataBase. I tried to store it using BLOB and String, in both cases it store the image and can retrieve it but when i convert it to Bitmap using BitmapFactory.decodeByteArray(...) it return null.

I have used this code, but it returns null

Bitmap  bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);

Answer

Uttam picture Uttam · Oct 1, 2011

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.