Android 使用SQLite儲存以及讀取Drawable對象

來源:互聯網
上載者:User

標籤:圖片   puts   壓縮   cto   函數   close   log   null   實現   

在進行Android開發過程中,我們經常會接觸到Drawable對象,那麼,若要使用資料庫來進行儲存及讀取,該如何??

一、儲存

//第一步,將Drawable對象轉化為Bitmap對象Bitmap bmp = (((BitmapDrawable)tmp.image).getBitmap());//第二步,聲明並建立一個輸出位元組流對象ByteArrayOutputStream os = new ByteArrayOutputStream();//第三步,調用compress將Bitmap對象壓縮為PNG格式,第二個參數為PNG圖片品質,第三個參數為接收容器,即輸出位元組流osbmp.compress(Bitmap.CompressFormat.PNG, 100, os);//第四步,將輸出位元組流轉換為位元組數組,並直接進行儲存資料庫操作,注意,所對應的列的資料類型應該是BLOB類型ContentValues values = new ContentValues();values.put("image", os.toByteArray());db.insert("apps", null, values);db.close();

代碼看起來比較繁瑣,是因為過程的確挺繁瑣的,不過可以簡單的總結為:

Drawable→Bitmap→ByteArrayOutputStream→SQLite

二、讀取

//第一步,從資料庫中讀取出相應資料,並儲存在位元組數組中  byte[] blob = cursor.getBlob(cursor.getColumnIndex("image"));  //第二步,調用BitmapFactory的解碼方法decodeByteArray把位元組數群組轉換為Bitmap對象  Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);  //第三步,調用BitmapDrawable建構函式產生一個BitmapDrawable對象,該對象繼承Drawable對象,所以在需要處直接使用該對象即可  BitmapDrawable bd = new BitmapDrawable(bmp);  

由於BitmapDrawable是Drawable的子類,所以直接使用就行了。

很顯然,讀取是儲存的相反過程,代碼思路也差不多,但實現起來簡單很多,總結思路為:

SQLite→byte[]→Bitmap→BitmapDrawable

Android 使用SQLite儲存以及讀取Drawable對象

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.