Android:从数据库中检索位图的问题 [英] Android: problem retrieving bitmap from database

查看:22
本文介绍了Android:从数据库中检索位图的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从 sqlite 数据库中检索图像时,我的 Bitmap 对象 bm 返回 null 值,谁能帮我..?

When I'm retrieving image from the sqlite database my Bitmap object bm return null value can any one help me..?

我发现我的数据库有问题..

I found problem in my database..

当我将字节数组以 blob 数据类型存储在数据库表中时,字节数组的大小为 2280..

When I store the byte array in blob data type in database table that time the size of the byte array was 2280..

但是当我使用选择查询检索那个 blob 数据类型时,我得到了大小为 12 的字节数组.

But when i retrieved that blob data type using select query I get the byte array within size 12.

我的代码是:

// Inserting data in database
byte[] b;  
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.icon);  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object  
b = baos.toByteArray();  
//here b size is 2280  
baos.close();  
try  
{  
mDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);  
mDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATABASE_TABLE
+ " (PICTURE BLOB);");    
mDB.execSQL("INSERT INTO "
+ MY_DATABASE_TABLE
+ " (PICTURE)"
+ " VALUES ('"+b+"');");  

}  
catch(Exception e)  
{  
Log.e("Error", "Error", e);  
}  

finally  
{  
if(mDB != null)  
mDB.close();  
}  


// Retriving data from database  
byte[] b1;  
Bitmap bm;  
mDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);  
try {  
mDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATABASE_TABLE
+ " (PICTURE BLOB);");  

Cursor c = mDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + ";", null);  
c.moveToFirst();  
if (c != null) {  
do {  
b1=c.getBlob(0)); //here b1 size is 12   
bm=BitmapFactory.decodeByteArray(b1, 0, b1.length);   
}while(c.moveToNext());  
}  

推荐答案

以下是我在写入数据库之前对图像进行编码的方法:

Here's how I encode the image before writing to the database:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray();  // write this to database as blob

然后像 from Cursor 一样解码:

And then decode it like the from Cursor:

ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);

这篇关于Android:从数据库中检索位图的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆