如何将图像文件数据从字节数组转换为位图?

135
我想将图像存储在SQLite数据库中。 我尝试使用BLOB和String来存储它,在这两种情况下都可以存储图像并且可以检索到它,但是当我使用BitmapFactory.decodeByteArray(...)将其转换为位图时,它返回null。
我已经使用了这段代码,但它返回null。
Bitmap  bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);

4
请阅读此页面“相关”部分的前5-10个链接。 - Mat
2
你在写入数据库之前对位图进行了编码吗? - Ron
3个回答

309

只需要尝试这样做:

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


2
如果您尝试从其他格式解码图像,则可能会出现“无法解码图像”的错误。 - lxknvlk
3
如果我需要连续执行这样的操作很多次,每次都创建新的Bitmap对象不会消耗资源吗?我能否将数组解码到现有的位图中? - Alex Semeniuk
当您只有图像像素缓冲区时,我会发布不同的答案。由于我的缓冲区中缺少宽度、高度和颜色,我一直得到null。希望这可以帮助您! - Julian

38

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以获取不同颜色选项。


2
mBitmaps是什么? - user924
@Julian,如何解决从Sqlite检索图像时出现“byte[]无法转换为java.lang.String”的问题?https://stackoverflow.com/questions/63658886/android-byte-cannot-be-cast-to-java-lang-integer?noredirect=1#comment112570298_63658886 - Kingg

0
我使用Uttam的答案为我的应用程序创建了Kotlin版本。 例如,可以使用registerForActivityResult来获取uri (参见Muntashir Akon的OnActivityResult方法已弃用,有什么替代方法?答案)。
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()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接