編輯:關於 Android 程式設計
想把圖片存進資料庫,本質上是三個轉換的串接:Drawable 轉 Bitmap、Bitmap 壓縮成 byte[]、存進 BLOB 欄位;讀出來時再反向走一遍。本文用一個完整的資料庫類別示範整個流程。
package com.android.test;
import java.io.ByteArrayOutputStream;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.provider.BaseColumns;
public class PictureDatabase extends SQLiteOpenHelper {
// 資料庫欄位
public static class PictureColumns implements BaseColumns {
public static final String PICTURE = "picture";
}
private Context mContext;
private static final String DATABASE_NAME = "picture.db"; // 資料庫名
private static final int DATABASE_Version = 1; // 版本號
private static final String TABLE_NAME = "picture"; // 表名
public PictureDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.mContext = context;
}
// 建立資料表並寫入初始資料
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "Create table " + TABLE_NAME + "(" + BaseColumns._ID
+ " integer primary key autoincrement,"
+ PictureColumns.PICTURE + " blob not null);";
db.execSQL(sql);
initDataBase(db, mContext);
}
// 把轉換後的圖片存入資料庫
private void initDataBase(SQLiteDatabase db, Context context) {
Drawable drawable = context.getResources()
.getDrawable(R.drawable.test_icon_resizer);
ContentValues cv = new ContentValues();
cv.put(PictureColumns.PICTURE, getPicture(drawable));
db.insert(TABLE_NAME, null, cv);
}
// 把 Drawable 轉成可儲存的 byte[]
private byte[] getPicture(Drawable drawable) {
if (drawable == null) {
return null;
}
BitmapDrawable bd = (BitmapDrawable) drawable;
Bitmap bitmap = bd.getBitmap();
ByteArrayOutputStream os = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 100, os);
return os.toByteArray();
}
// 版本更新時重建資料表
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = " DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
}
整個轉換的關鍵在這三行:
ByteArrayOutputStream os = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 100, os);
return os.toByteArray();
思路是「借道位元組串流」。compress() 把 Bitmap 依指定格式寫入串流,寫完之後再從串流中取出內含的位元組陣列。這裡用 PNG 格式並將品質設為 100,因為 PNG 是無失真壓縮,第二個參數對它實際上沒有作用;若改用 JPEG,該參數才會作為 0~100 的品質依據。
拿到 byte[] 之後,塞進型別為 blob 的欄位即可:
ContentValues cv = new ContentValues();
cv.put(PictureColumns.PICTURE, getPicture(drawable));
db.insert(TABLE_NAME, null, cv);
package com.android.test;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
public class TestPicture extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView iv = new ImageView(this);
if (getDrawable().size() != 0) {
iv.setImageDrawable(getDrawable().get(0));
}
setContentView(iv);
}
private ArrayList<Drawable> getDrawable() {
PictureDatabase pd = new PictureDatabase(this);
SQLiteDatabase sd = pd.getWritableDatabase();
ArrayList<Drawable> drawables = new ArrayList<Drawable>();
// 查詢資料庫
Cursor c = sd.query("picture", null, null, null, null, null, null);
// 走訪每一筆資料
if (c != null && c.getCount() != 0) {
while (c.moveToNext()) {
// 取出位元組
byte[] b = c.getBlob(c.getColumnIndexOrThrow(
PictureDatabase.PictureColumns.PICTURE));
// 還原成 Drawable
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length, null);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
Drawable drawable = bitmapDrawable;
drawables.add(drawable);
}
}
return drawables;
}
}
還原的關鍵同樣是三行,剛好是寫入時的逆操作:
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length, null);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
Drawable drawable = bitmapDrawable;

把圖片存進 SQLite 聽起來方便,實際上有幾個明確的缺點值得先知道。
第一,資料庫會快速膨脹。一張相片動輒數 MB,轉成 byte[] 後還要加上 Base64 或二進位儲存,備份、同步、遷移的成本都會變高,而且 SQLite 對單一欄位存有大型 BLOB 的效能並不理想。
第二,記憶體壓力。範例中的 getDrawable() 一次把所有圖片全部解碼進記憶體,圖片一多就會 OutOfMemoryError。實務上應該配合 BitmapFactory.Options 的 inSampleSize 做縮圖解碼,或直接改用 Glide、Picasso 這類影像載入框架。
第三,onUpgrade() 直接 DROP 重建,會讓使用者既有資料全部消失。正式環境請改為撰寫遷移邏輯,或使用 ALTER TABLE 逐版本調整。
結論:資料庫存圖片適合「小圖示、快取縮圖、需要與其他資料一起交易的少量圖像」這類場景。若是使用者的大尺寸照片,標準做法是把檔案存到 App 專屬目錄或 MediaStore,資料庫只存路徑或 Uri。
Android SeekBar 實作:用 Handler 訊息機制控制進度條自動遞增
本文分享一個以 Handler 訊息處理機制來操作 SeekBar 的實例,示範如何讓進度條可拖動、也能夠自動遞增,供需要的朋友參考。 這個案例很簡單,重點在於用 Han
自定義 View 繪圖篇(一):基礎圖形的繪製
一、Paint 與 Canvas 繪圖離不開兩個工具:筆和紙。這里 Paint 相當於筆,Canvas 相當於紙。需要注意的是,Canvas(畫布)是無限大、沒有邊界的,
Android 實現帶磁性的懸浮窗效果
本文示範如何實現一個「帶磁性」的懸浮窗,效果類似 360 的那個綠色小人。它主要具備三個特性:懸浮在所有窗體之上、能吸附於螢幕邊緣、並支援點擊。以下把這三點封裝成一個 F
Android 學習筆記:Intent Filter 與自製瀏覽器
Intent Filter 的作用Intent Filter 用來告訴系統,某個元件可以處理哪些 Intent。它由 action、category 與 data 等條件