Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片存進 SQLite 再讀出來:Drawable 與 BLOB 的雙向轉換

編輯:關於 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);
    }
}

核心:Drawable 怎麼變成 byte[]

整個轉換的關鍵在這三行:

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);

第二步:從資料庫讀回來並還原成 Drawable

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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved