2011-10-01 80 views
77

我想将图像存储在SQLite DataBase中。 我试图存储它使用BLOBString,在这两种情况下它存储 图像,可以检索它,但是当我将它转换为Bitmap使用 BitmapFactory.decodeByteArray(...)它返回null。如何将字节数组转换为位图

我已经使用这个代码,但它返回null

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

请阅读此页上的“相关”部分中的第5-10链接。 – Mat

+0

在写入数据库之前,您是否对位图进行了编码? – Ronnie

回答

200

就试试这个:

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

如果bitmapdata是字节数组,然后让Bitmap像这样做:

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

返回解码的Bitmapnull如果图像无法解码。

+13

何时图像不能解码? –

+2

如果您尝试从其他格式的图像解码,则无法解码图像 – lxknvlk

+1

如果我需要按顺序执行多次这样的操作,该怎么办?每次创建新的Bitmap对象是否耗费资源?我可以以某种方式将我的数组解码到现有的位图中吗? –

8

Uttam的答案没有为我工作。我刚刚得到了空当我这样做:

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

在我的情况下,位图数据只有像素的缓冲,所以它是IMPOSIBLE的功能decodeByteArray猜测其宽度,高度和颜色位数使用。所以,我想这和它的工作:

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

检查https://developer.android.com/reference/android/graphics/Bitmap.Config.html不同的颜色可供选择