sqlite圖片是怎么儲(chǔ)存的呢冬念?其實(shí)是二進(jìn)制的方式存儲(chǔ)的
blob
代表使用二進(jìn)制儲(chǔ)存 (更多類型參考:數(shù)據(jù)庫簡介)
在創(chuàng)建表的地方,VALUE_PIC代表存儲(chǔ)圖片字段,blob代表這個(gè)字段是以二進(jìn)制儲(chǔ)存的。
/*創(chuàng)建表語句 語句對大小寫不敏感 create table 表名(字段名 類型闷供,字段名 類型乡恕,…)*/
private final String CREATE_PERSON = "create table " + TABLE_NAME_PERSON + "(" +
VALUE_ID + " integer primary key," +
VALUE_NAME + " text ," +
VALUE_ISBOY + " integer," +
VALUE_AGE + " ingeter," +
VALUE_ADDRESS + " text," +
VALUE_PIC + " blob" +
")";
那怎么存拗踢,其實(shí)存的是字節(jié)數(shù)組byte[]
/**
* 添加數(shù)據(jù)
* @param model 數(shù)據(jù)模型
* @return 返回添加數(shù)據(jù)有木有成功
*/
public PersonModel addPersonDataReturnID(PersonModel model) {
//把數(shù)據(jù)添加到ContentValues
ContentValues values = new ContentValues();
values.put(VALUE_NAME, model.getName());
values.put(VALUE_AGE, model.getAge());
values.put(VALUE_ISBOY, model.getIsBoy());
values.put(VALUE_ADDRESS, model.getAddress());
//這里存儲(chǔ)圖片,model.getPic() 是一個(gè)字節(jié)數(shù)組
values.put(VALUE_PIC, model.getPic());
//添加數(shù)據(jù)到數(shù)據(jù)庫
long index = getWritableDatabase().insert(TABLE_NAME_PERSON, null, values);
//不等于-1表示添加成功(可以看insert源碼)
if (index != -1) {
model.setId(index);
return model;
} else {
return null;
}
}
怎么將圖片變成字節(jié)數(shù)組?
/**
* @param resourceID 圖片資源id
* @return 將圖片轉(zhuǎn)化成byte
*/
private byte[] picTobyte(int resourceID)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = context.getResources().openRawResource(resourceID);
Bitmap bitmap = BitmapFactory.decodeStream(is);
//壓縮圖片伐蒋,100代表不壓縮(0~100)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
那怎么取出來呢?
//查詢?nèi)繑?shù)據(jù)
Cursor cursor = getWritableDatabase().query(TABLE_NAME_PERSON, null, null, null, null, null, null, null);
byte pic[] = cursor.getBlob(cursor.getColumnIndex(VALUE_PIC));
Bitmap b = BitmapFactory.decodeByteArray(pic, 0, pic.length);
holder.pic.setImageBitmap(b);
sqlite也無非就創(chuàng)建迁酸、增先鱼、刪、改奸鬓、查焙畔、更新。