2

I have 5 Mb worth of images that I want to put into an sqlite db, in blob fields. After the insertion, the db is around 50Mb.

This is how I get the 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();
}

This is how I insert them into the db:

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");
    }
}

What am I screwing up? :)

edit: the problem was, I should not be putting bitmaps into the database, but just the raw (compressed in jpeg format)files. So for reference, here is a correct way of getting a byte[] from a bitmap file, so it's still small in size:

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();
    }
4

2 回答 2

3

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

于 2013-04-26T14:06:09.953 回答
0

将图像作为 blob 存储在数据库中可能不是一个好主意。有几个原因...

  • 在 Android 上,您的数据库文件存储在手机的内部存储器中,而不是 SD 卡中。由于手机的内部存储空间可能非常有限,因此将大容量内容存储在 SD 卡上总是一个好主意。虽然,此参数在不允许扩展存储的较新设备上可能无效。
  • 如果用户决定卸载您的应用程序,图像也会随之而来。

我建议将图像保存到 SD 卡,并将文件路径存储在数据库中。

于 2013-04-26T14:04:18.913 回答