關於SQLite 數據庫 讀寫圖片的問題


數據庫中圖片的字段名爲image ,數據類型 是blob

--------------------------------以下是存入------------------

ByteArrayOutputStream baos = new ByteArrayOutputStream();

--------------------------第一種圖片數據來源-----------------------------------------------------------
//如果圖片數據來源是ImageView組件中的圖片,可以用以下方法,mImageview_save是個ImageView的對象
//PNG是存入的圖片格式,100是圖片質量(0-100)
((BitmapDrawable) mImageview_save.getDrawable()).getBitmap()

.compress(CompressFormat.PNG, 100, baos);

---------------------------第二種圖片數據來源---------------------------------------------------------
//如果圖片數據來源是Drawable型,可以用以下方法,drawableimage是Drawable對象

((BitmapDrawable) drawableimage).getBitmap().compress(
CompressFormat.PNG, 100, baos);

---------------------------第三種圖片數據來源---------------------------------------------------------
//如果圖片數據來源是資源ID,可以用以下方法,先將對應ID的圖片對象轉爲drawable型
Resources res = this.getResources();
Drawable mDrawable = res.getDrawable(R.drawable.xx);

((BitmapDrawable) mDrawable).getBitmap().compress(
CompressFormat.PNG, 100, baos);
-----------------------------------------------------------------------------------------------

byte[] savebyte = baos.toByteArray();

//將byte[]數據插入數據庫
mdb.insertImage("cy5",savebyte);

----------------------以下是讀取---------------------------------

Cursor mCursor;

mCursor = mdb.queryImage("cy5");

startManagingCursor(mCursor);

mCursor.moveToFirst();

byte[] getbyte = mCursor.getBlob(mCursor.getColumnIndex("image"));

ByteArrayInputStream bais = new ByteArrayInputStream(getbyte);

mImageview_get.setImageDrawable(Drawable.createFromStream(bais, "photo"));

//photo是標識,可以不寫,據說是調試的時候可能會用上.


發佈了6 篇原創文章 · 獲贊 0 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章