2010-02-15 65 views
5

當我從sqlite數據庫中檢索圖像時,我的位圖對象bm返回空值,任何人都可以幫助我..?Android:從數據庫檢索位圖的問題

我發現在我的數據庫的問題..

當我存儲字節數組中的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

同樣的問題! 你有沒有找到解決方案? – 2010-06-23 11:02:33

回答

10

以下是我寫的DAT之前編碼圖像ABASE:

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

然後就像從遊標對其進行解碼:這裏

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