想在SQLite中存图片,有两种方式,一种是存图片所在路径,一种就是存二进制文件,在SQLite中存二进制图片选择BLOB类型
存储
private void saveImageToDb(SQLiteDatabase db, Bitmap bitmap, String id) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
ContentValues values = new ContentValues();
values.put("img", os.toByteArray()); // 对应表字段img
db.update("table_name", values, "id = ?", new String[]{id}); // 更新到table_name表指定id的数据
}
读取
private Bitmap readImageFromDb(String id) {
Bitmap img = null;
byte[] bytes;
String sql = "SELECT * FROM table_name WHERE id = ?";
Cursor cursor = db.rawQuery(sql, new String[]{id});
if (cursor.moveToFirst()) {
if ((bytes = cursor.getBlob(cursor.getColumnIndex("img"))) != null) {
img = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
}
cursor.close();
return img;
}