1. 程式人生 > >android sqlite 儲存圖片

android sqlite 儲存圖片

Android資料庫中存取圖片通常使用兩種方式,一種是儲存圖片所在路徑,二是將圖片以二進位制的形式儲存(sqlite3支援BLOB資料型別)。對於兩種方法的使用,好像第二種方法不如第一種方法更受程式設計師歡迎,他們認為,在很多資料庫語言裡,處理大欄位都是不容易的,像圖片這樣的檔案放在資料庫裡會有問題:對資料庫的讀寫速度永遠趕不上檔案系統的處理速度,使資料庫變得巨大;但也有很多人認為像圖片這樣的資料存放在資料庫中也有好處:易於備份,且備份速度絕對比備份檔案快,比較容易資料遷移等等。其實這兩種方法都有優缺點,具體使用哪種方法要視情況而定。個人傾向於使用資料庫存取圖片,因為個人認為存到資料庫裡的資料不會因外部資料的變化而丟失改變,比如你拍照獲得一張圖片,如果是將路徑存到資料庫,當這張照片被刪除之後,下次讀取資料庫就得不到想要的結果了。接下來詳細介紹資料庫存取圖片的方法:

  1.從資源中獲取Bitmap物件

1     Resources res = getResources();
2     Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.icon);

  2.把圖片轉換成位元組

複製程式碼
1 public byte[] img(int id)
2 {
3      ByteArrayOutputStream baos = new ByteArrayOutputStream();
4      Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(id)).getBitmap();
5 bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); 6 return baos.toByteArray(); 7 }
複製程式碼

  3.在資料庫中插入圖片

複製程式碼
//在資料庫建立時,圖片欄位的資料型別儲存為 BLOB資料庫插入操作
public void onCreate(SQLiteDatabase db)
{ 
    String sql = "create table " + TB_NAME + " ( " + ID + " integer primary key , " + IMAGE + " BLOB ) ";
    db.execSQL(sql);
} 

//將圖片一位元組形式儲存資料庫讀取操作 public long insert(byte[] img) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(IMAGE, img); long result = db.insert(TB_NAME, null, cv); return result; }
複製程式碼

  4.獲取存入資料庫的圖片(Bitmap)

複製程式碼
public Bitmap getBmp(int position) 
{
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = select(TB_NAME);
    cursor.moveToPosition(position);
    byte[] in = cursor.getBlob(cursor.getColumnIndex(IMAGE));
    Bitmap bmpout = BitmapFactory.decodeByteArray(in, 0, in.length);
    return bmpout;
}
複製程式碼

  //imgView.setImageBitmap(bm);

  5.轉換獲取的圖片(Bitmap)為Drawable

複製程式碼
1 public Drawable chage_to_drawable(Bitmap bp)
2 {
3     //因為BtimapDrawable是Drawable的子類,最終直接使用bd物件即可。
4     Bitmap bm=bp; 
5     BitmapDrawable bd= new BitmapDrawable(getResource(), bm); 
6     return bd;
7 }
複製程式碼