2012-01-05 31 views
1

我正在開發一個應用程序,它在sqlite中存儲一些靜態圖像,我想在imageview中檢索相同的圖像。 我該怎麼做 謝謝。我怎麼能存儲圖像和檢索相同的sqlite-android

+0

在SD卡上存儲圖像,使用SD卡的路徑並將其存儲在數據庫中。稍後,當您需要圖像時,只需使用此路徑檢索圖像並在圖像視圖中顯示。 – 2012-01-05 08:24:05

+0

我想將圖像作爲blob存儲在數據庫中。我不想使用文件路徑。 – user1002448 2012-01-05 09:40:06

回答

7

sqlite3支持blob類型,您可以使用blob類型保存位圖內容。

但是,blob類型具有大小限制,並且保存爲blob類型很困難。

所以,我建議保存位圖本地或SD卡上,並將路徑保存在數據庫中。

加入

表定義一個名爲「圖像」使用blob類型的列

Bitmap map = ...; 
    ByteArrayOutputStream bufferStream = new ByteArrayOutputStream(16*1024); 
    map.compress(CompressFormat.JPEG, 80, bufferStream); 
    byte[] bytes = bufferStream.toByteArray(); 
    ContentValues values = new ContentValues(); 
    values.put("image", bytes); 

轉換圖像字節數組,使用SQLiteDatabase類方法或內容提供者,只要你喜歡:

public long insert (String table, String nullColumnHack, ContentValues values)

插入表格,所以它保存圖像到blob

然後:在查詢blob數據,你可以這樣創建圖像:

 BitmapFactory.Options option2 = new BitmapFactory.Options(); 
     option2.inPreferredConfig = Bitmap.Config.RGB_565; 
     // added for reducing the memory 
     option2.inDither = false; 
     option2.inPurgeable = true; 
     return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, option2); 

希望它可以實現你的要求。 - ):

+0

我想要存儲確切的圖像,而不是路徑。我知道我需要使用blob。但我沒有得到如何實現它。 – user1002448 2012-01-05 09:41:15

+0

真棒,完美的作品,謝謝!關於將圖像存儲在SD卡上:用戶可能會移動/刪除它。而某些設備可能沒有SD卡開始。 – Buffalo 2012-10-03 14:28:10