Android 在SQLite中存取二进制图片

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

想在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;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值