Android數(shù)據(jù)庫中存取圖片通常使用兩種方式,一種是保存圖片所在路徑,二是將圖片以二進(jìn)制的形式存儲(chǔ)(sqlite3支持BLOB數(shù)據(jù)類型)。對(duì)于兩種方法的使用,好像第二種方法不如第一種方法更受程序員歡迎,他們認(rèn)為,在很多數(shù)據(jù)庫語言里,處理大字段都是不容易的,像圖片這樣的文件放在數(shù)據(jù)庫里會(huì)有問題:對(duì)數(shù)據(jù)庫的讀寫速度永遠(yuǎn)趕不上文件系統(tǒng)的處理速度,使數(shù)據(jù)庫變得巨大;但也有很多人認(rèn)為像圖片這樣的數(shù)據(jù)存放在數(shù)據(jù)庫中也有好處:易于備份,且備份速度絕對(duì)比備份文件快,比較容易數(shù)據(jù)遷移等等。其實(shí)這兩種方法都有優(yōu)缺點(diǎn),具體使用哪種方法要視情況而定。個(gè)人傾向于使用數(shù)據(jù)庫存取圖片,因?yàn)閭€(gè)人認(rèn)為存到數(shù)據(jù)庫里的數(shù)據(jù)不會(huì)因外部數(shù)據(jù)的變化而丟失改變,比如你拍照獲得一張圖片,如果是將路徑存到數(shù)據(jù)庫,當(dāng)這張照片被刪除之后,下次讀取數(shù)據(jù)庫就得不到想要的結(jié)果了。接下來詳細(xì)介紹數(shù)據(jù)庫存取圖片的方法:
1、把圖片轉(zhuǎn)換為字節(jié)
private byte[]img(Bitmap bitmap){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } 2、把圖片存儲(chǔ)到數(shù)據(jù)庫
假設(shè)獲取的圖片為bitmap,數(shù)據(jù)庫有一張User表,存儲(chǔ)的屬性為byte[]headshot
public class User extends DataSupport { private byte[] headshot;//頭像 public User(){ super(); } public User(byte[]headshot){ super(); this.headshot=headshot; } public byte[] getHeadshot() { return headshot; } public void setHeadshot(byte[] headshot) { this.headshot = headshot; } } 對(duì)圖片進(jìn)行保存
//獲取到圖片 Bitmap headShot=BitmapFactory.decodeFile(imagePath); //把圖片轉(zhuǎn)換字節(jié)流 byte[]images=img(headShot); //找到用戶 User users=DataSupport.findFirst(User.class); //保存 users.setHeadshot(images); users.save();
4、獲取圖片
User mUser=DataSupport.findFrist(User.class); byte[]images=mUser.getHeadshot(); Bitmap bitmap=BitmapFactory.decodeByteArray(images,0,images.length);
好了,到此完成對(duì)數(shù)據(jù)庫存取圖片。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注