android - sqlite 中的图像巨大

标签 android image sqlite

我有 5 Mb 的图像,我想将它们放入 sqlite 数据库的 blob 字段中。 插入后db大约50Mb。

这就是我获取byte[]的方式:

private static byte[] getByteArrayFromFileName(String filename) {
    int id = context.getResources().getIdentifier(filename, "raw", context.getPackageName());
    ByteArrayOutputStream blob = new ByteArrayOutputStream();
    BitmapFactory.decodeResource(context.getResources(), id).compress(CompressFormat.PNG, 0, blob);
    return blob.toByteArray();
}

这就是我将它们插入数据库的方式:

public void createImage(SQLiteDatabase database, Image image) throws DbException {
    ContentValues values = new ContentValues();
    values.put(ImageTable.DATA, image.data);
    values.put(ImageTable.TYPE_ID, image.type.getValue());
    values.put(ImageTable.LEVELID, image.levelId);
    values.put(ImageTable.ID, image.id);

    if (database.replace(ImageTable.TABLE_NAME, null, values) == -1) {
        throw new DbException("createImage insertion error");
    }
}

我搞砸了什么? :)

编辑:问题是,我不应该将位图放入数据库,而应该将原始文件(以 jpeg 格式压缩)放入数据库中。因此,作为引用,这里是从位图文件获取 byte[] 的正确方法,因此它的大小仍然很小:

private static byte[] getByteArrayFromRawByFileName(Context context, String filename) throws IOException {
        int id = context.getResources().getIdentifier(filename, "raw", context.getPackageName());
        InputStream is = context.getResources().openRawResource(id);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int bytesRead;
        byte[] b = new byte[1024];
        while ((bytesRead = is.read(b)) != -1) {
            bos.write(b, 0, bytesRead);
        }
        return bos.toByteArray();
    }

最佳答案

问题可能是您正在使用 JPEG图像作为源,但在插入之前将它们编码为 PNG我相信这就是 10 倍增长的原因。您的getByteArrayFromFileName () 也是失败的,因为你有一个文件,你可以将其读作 byteArray没有BitmapFactory涉及

关于android - sqlite 中的图像巨大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238240/

相关文章:

android - 旋转器功能不适用于 Android 6.0.1

java - Dagger 2 : Provide same instance between multiple Component with same Scope on different library modules

java - 在java中将TIF图像添加到Jlist或Frame中

android - 上传图片/照片/图像 facebook (android)

mysql - 多个表上的 sequelize 查询中的竞争条件

android - Android SDK更新后新项目创建问题

java - 具有许多不同 View 的 ListView 适配器

silverlight - 在 XAML 中绑定(bind)图像源

sql - 在一个语句中对同一字段进行多次 SELECT

python - SQLAlchemy 不存在于子选择上?