将位图存储为Sqlite中的BLOB是个好主意吗? [英] Is it a good idea to store bitmap as BLOB in Sqlite?

查看:137
本文介绍了将位图存储为Sqlite中的BLOB是个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在sqlite数据库中存储了太多位图(作为BLOB),而在取回它们时,我会收到一个奇怪的异常(即使Throwable也无法捕获,但我每次都能在LogCat中看到它):

If I store too many bitmaps (as BLOB) in my sqlite database, while retrieving them back I get strange exception (which I can't catch even as Throwable, but I can see it in LogCat every time):

Failed to read row 2, column 0 from a CursorWindow which has 2 rows, 8 columns

当我不存储BLOB时,不会出现此类异常.也许我应该将图像存储在手机内存中,并保留数据库uris来存储这些图像?

When I don't store BLOBs, I don't get such exceptions. Maybe I should store images at phone memory and keep at database uris to this images?

出什么问题了?有人可以告诉我吗?

What is the problem? Could anyone tell me?

推荐答案

通常,将位图/图像存储在数据库中通常不是一个好主意,这根本没有效率.

Usually not a good idea to store bitmaps/images in general on your database, it's not efficient at all.

您应该将位图另存为图像,并将路径存储在数据库中.

You should save the bitmaps as images and store the paths on the database.

此问题中对此进行了讨论.

但是...如果出于某种原因真的要存储它,也可以尝试将图像编码为Base64 String,然后将其存储在数据库中.

But... If you're really into storing that for whatever reason, you could also try to encode the image as a Base64 String, and store it on your DB.

Android为此具有 Base64 class .尝试使用以下代码片段进行编码:

Android has the Base64 class for this. Try to use the following snippet to encode:

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // Could be Bitmap.CompressFormat.PNG or Bitmap.CompressFormat.WEBP
byte[] bai = baos.toByteArray();

String base64Image = Base64.encodeToString(bai, Base64.DEFAULT);

// Call your method to save this string on the DB here.

您将不得不对其进行解码,请尝试以下操作:

And you'll have to decode it try the following:

byte[] data = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap bm;
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
bm = BitmapFactory.decodeByteArray(data, 0, data.length, opt);

// Now do whatever you want with the Bitmap.

您可以在此处看到Bitmap类的文档. >.

You can see the docs for the Bitmap class here.

这篇关于将位图存储为Sqlite中的BLOB是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆