建立數據庫
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database_name";
// Table Names
private static final String DB_TABLE = "table_image";
// column names
private static final String KEY_NAME = "image_name";
private static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+
KEY_NAME + " TEXT," +
KEY_IMAGE + " BLOB);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
}
在數據庫中插入:
public void addEntry(String name, byte[] image) throws SQLiteException{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_IMAGE, image);
database.insert(DB_TABLE, null, cv);
}
檢索數據:
byte[] image = cursor.getBlob(1);
注:
- 之前插入到數據庫中,你需要位圖圖像先轉換成字節數組,然後利用數據庫查詢應用它。
- 當從數據庫中檢索時,你肯定有一個字節數組的圖像,你需要做的是將字節數組轉換回原始圖像。所以,你必須利用BitmapFactory解碼。
下面是我希望的實用工具類可以幫助你:
public class DbBitmapUtility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
進一步閱讀
如果你不熟悉如何插入和檢索到數據庫,通過這個tutorial 。
這是更好地在這裏 – 2012-08-03 06:03:14
[建議](HTTP POST代碼://計算器.com/a/9141116/996493) – Lucifer 2012-08-03 06:03:22
Chech [this out](http://stackoverflow.com/questions/4342798/displaying-image-from-the-sqlite-database-using-cursor-in-android)。 – tolgap 2012-08-03 06:03:50