我有 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/