【问题标题】:How to convert image file data in a byte array to a Bitmap?如何将字节数组中的图像文件数据转换为位图?
【发布时间】:2011-11-29 01:00:53
【问题描述】:

我想将图像存储在SQLite DataBase。 我尝试使用BLOBString 存储它,在这两种情况下它都存储 图像并且可以检索它但是当我将它转换为Bitmap 使用 BitmapFactory.decodeByteArray(...) 它返回 null。

我用过这段代码,但它返回null

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

【问题讨论】:

  • 请阅读本页“相关”部分的前 5-10 个链接。
  • 在写入数据库之前是否对位图进行了编码?

标签: android arrays sqlite bitmap


【解决方案1】:

试试这个:

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

返回解码后的Bitmap,如果图像无法解码,则返回null

【讨论】:

  • 图像如果是您尝试解码的其他格式,则无法解码
  • 如果我需要依次执行多次这样的操作怎么办?每次创建新的 Bitmap 对象不是很耗费资源吗?我可以以某种方式将我的数组解码为现有位图吗?
  • 当您只有图像像素的缓冲区时,我会发布一个不同的答案。由于缓冲区中缺少 with、height 和 color,我总是得到 null。希望对您有所帮助!
【解决方案2】:

Uttam 的答案对我不起作用。当我这样做时,我得到了 null:

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

在我的例子中,bitmapdata 只有像素的缓冲区,所以函数 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(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

查看https://developer.android.com/reference/android/graphics/Bitmap.Config.html 了解不同的颜色选项

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-01-14
  • 2013-07-29
  • 2018-08-21
  • 2011-03-07
  • 2018-05-06
  • 1970-01-01
相关资源
最近更新 更多