127

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);
user3840170
  • 11,878
  • 11
  • 37
Vasu
  • 2,513
  • 5
  • 18
  • 17

2 Answers2

291

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.

manfcas
  • 1,855
  • 6
  • 28
  • 46
Uttam
  • 11,887
  • 3
  • 30
  • 30
  • 2
    image could not be decoded if it is in other format that you are trying to decode from – lxknvlk Mar 28 '15 at 12:23
  • 2
    What if I need to perform such an operation many times in sequence? Isn't it resource-consuming to create new Bitmap object every time? Can I somehow decode my array into existing bitmap? – Alex Semeniuk Apr 16 '15 at 11:27
  • I post a different answer when you just have a buffer of the image pixel. I was getting always null because of the lack of with, height and color in my buffer. Hope it helps! – Julian Nov 30 '16 at 07:19
34

The answer of Uttam didnt work for me. I just got null when I do:

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

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

Derzu
  • 6,253
  • 1
  • 49
  • 56
Julian
  • 2,015
  • 22
  • 17
  • 2
    what is mBitmaps? – user924 Apr 04 '18 at 09:55
  • @Julian How to byte[] cannot be cast to java.lang.String when retreving image from Sqlite https://stackoverflow.com/questions/63658886/android-byte-cannot-be-cast-to-java-lang-integer?noredirect=1#comment112570298_63658886 – Kingg Aug 30 '20 at 16:03