想在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;
}
本文介绍在SQLite数据库中存储图片的两种方法:一是保存图片路径,二是将图片转换为二进制文件并使用BLOB类型存储。文章提供了具体的代码示例,包括如何将Bitmap对象压缩并保存到数据库以及从数据库中读取并还原为Bitmap。
1429

被折叠的 条评论
为什么被折叠?



