如何将位图保存到数据库?

11

我想知道如何将位图保存在数据库中。我已经在数据库中创建了表格:

@Override
public void onCreate(SQLiteDatabase db)
{
    db.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,image BLOB)");         
}    

我的问题是我无法插入图片,请告诉我需要以哪种格式插入图片。


1
我想知道为什么你要将它保存到数据库中。你可以将图像保存在某个地方,并将其路径存储在数据库中。 - Aman Alam
4个回答

16

如果您拥有位图图像,则可以执行以下操作。

Bitmap photo = <Your image>
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();

然后您可以使用以下方法将数据保存在表中。

db = YourDBHelper.getInstance(ctx).getWritableDatabase();    
ContentValues values = new ContentValues();         
values.put("image", bArray);            
db.insert(TABLE_NAME , null, values);

除了不显示“创建表”代码之外,这应该是被接受的。 - Chad Bingham
1
不建议将图像存储在数据库中,而是应将其存储在文件系统中,并将路径保存在数据库表中。 - Ewoks
我们应该将图片存储到用户手机内存还是SD卡中?在SQLite中存储字节数组是否低效? - Vishal Kumar

10

如果您想这样做,您需要使用 blob。但为什么要这样做呢?我不会将图像存储到数据库中。最好将图像存储在SD卡上,然后将其路径存储到数据库中。通常,数据库安装在手机内存中,这将使手机内存被填满。



0

试试这个

InputStream is = mycon.getAssets().open("data/Images/img1");
                if (is.available() == -1) {
                    Log.v(null, "Images not read to Input stream");
                }
                if (is != null) {
                    BufferedInputStream bis = new BufferedInputStream(is, 128);
                    ByteArrayBuffer barb = new ByteArrayBuffer(128);
                    // read the bytes one by one and append it into the
                    // ByteArrayBuffer barb
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                        barb.append((byte) current);
                    }
                    values.put("imageData", barb.toByteArray());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接