我想将图像存储在
SQLite DataBase
中。
我尝试使用 BLOB
和 String
来存储它,在这两种情况下它都存储
图像并可以检索它,但是当我使用它将其转换为 Bitmap
时
BitmapFactory.decodeByteArray(...)
它返回null。
我使用了这段代码,但它返回null
Bitmap bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
试试这个:
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
。
Uttam 的答案对我不起作用。当我这样做时,我刚刚得到空:
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 不同的颜色选项
我在我的应用程序中使用了 Uttam 答案的 Kotlin 版本。 例如,可以使用
registerForActivityResult
获取 uri
(请参阅 OnActivityResult 方法已弃用,有什么替代方法? Muntashir Akon 的回答)
var uri: Uri? = null
var bitmap: Bitmap? = null
// enter the code to get the uri
//
try {
val source = ImageDecoder.createSource(
context.contentResolver,
uri!!
)
bitmap = ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSampleSize(1) // shrinking by
decoder.isMutableRequired = true // this resolve the hardware type of bitmap problem
}
} catch (e: Exception) {
e.printStackTrace()
}