欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android利用LitePal操作數(shù)據(jù)庫存取圖片

 更新時(shí)間:2017年08月03日 09:23:16   作者:你好好笑的樣子i  
這篇文章主要為大家詳細(xì)介紹了Android利用LitePal操作數(shù)據(jù)庫存取圖片的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

Android數(shù)據(jù)庫中存取圖片通常使用兩種方式,一種是保存圖片所在路徑,二是將圖片以二進(jìn)制的形式存儲(sqlite3支持BLOB數(shù)據(jù)類型)。對于兩種方法的使用,好像第二種方法不如第一種方法更受程序員歡迎,他們認(rèn)為,在很多數(shù)據(jù)庫語言里,處理大字段都是不容易的,像圖片這樣的文件放在數(shù)據(jù)庫里會有問題:對數(shù)據(jù)庫的讀寫速度永遠(yuǎn)趕不上文件系統(tǒng)的處理速度,使數(shù)據(jù)庫變得巨大;但也有很多人認(rèn)為像圖片這樣的數(shù)據(jù)存放在數(shù)據(jù)庫中也有好處:易于備份,且備份速度絕對比備份文件快,比較容易數(shù)據(jù)遷移等等。其實(shí)這兩種方法都有優(yōu)缺點(diǎn),具體使用哪種方法要視情況而定。個人傾向于使用數(shù)據(jù)庫存取圖片,因?yàn)閭€人認(rèn)為存到數(shù)據(jù)庫里的數(shù)據(jù)不會因外部數(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、把圖片存儲到數(shù)據(jù)庫

假設(shè)獲取的圖片為bitmap,數(shù)據(jù)庫有一張User表,存儲的屬性為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; 
  } 
} 

對圖片進(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); 

好了,到此完成對數(shù)據(jù)庫存取圖片。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論