当我从sqlite数据库中检索图像时,我的Bitmap对象bm
返回null值可以帮助我吗?
我在我的数据库中发现了问题..
当我将字节数组存储在数据库表中的blob数据类型中时,字节数组的大小为2280 ..
但是当我使用select查询检索该blob数据类型时,我获得了大小为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());
}
答案 0 :(得分:10)
以下是我在写入数据库之前对图像进行编码的方法:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray(); // write this to database as blob
然后解码它就像来自Cursor:
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);