android sqlite blob


BOLB表示二進制大對象,這種數據類型通過用來保存圖片,圖象,視頻等。

 

使用場景:

http://blog.sina.com.cn/s/blog_8cfbb99201012oqn.html

 

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
// 重寫構造方法
public MySQLiteOpenHelper(Context context, String name,
CursorFactory cursor, int version) {
super(context, name, cursor, version);
}

// 創建數據庫的方法
public void onCreate(SQLiteDatabase db) {
// 創建一個數據庫,表名:imagetable,字段:_id、image。
db.execSQL("CREATE TABLE imagetable (_id INTEGER PRIMARY KEY AUTOINCREMENT,image BLOB)");
}

// 更新數據庫的方法
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

// 創建助手類的實例
// CursorFactory的值為null,表示采用默認的工廠類
mySQLiteOpenHelper = new MySQLiteOpenHelper(this, "saveimage.db", null,1);
// 創建一個可讀寫的數據庫
mydb = mySQLiteOpenHelper.getWritableDatabase();

//將圖片轉化為位圖
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(), R.drawable.erweima);

int size=bitmap1.getWidth()*bitmap1.getHeight()*4;
//創建一個字節數組輸出流,流的大小為size
ByteArrayOutputStream baos=new ByteArrayOutputStream(size);
//設置位圖的壓縮格式,質量為100%,並放入字節數組輸出流中 bitmap1.compress(Bitmap.CompressFormat.PNG, 100, baos);
//將字節數組輸出流轉化為字節數組byte[]
byte[] imagedata1=baos.toByteArray();

//將字節數組保存到數據庫中
ContentValues cv=new ContentValues();
cv.put("_id", 1);
cv.put("image", imagedata1);
mydb.insert("imagetable", null, cv);
//關閉字節數組輸出流
baos.close();

從數據庫中查詢的方法
//創建一個指針
Cursor cur=mydb.query("imagetable", new String[]{"_id","image"}, null, null, null, null, null);
byte[] imagequery=null;
if(cur.moveToNext()){
//將Blob數據轉化為字節數組imagequery=cur.getBlob(cur.getColumnIndex("image"));
}
//將字節數組轉化為位圖
Bitmap imagebitmap=BitmapFactory.decodeByteArray(imagequery, 0, imagequery.length);
iv1=(ImageView) findViewById(R.id.imageView1);
//將位圖顯示為圖片
iv1.setImageBitmap(imagebitmap);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM