我想知道如何将位图保存在数据库中。我已经在数据库中创建了表格:
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,image BLOB)");
}
我的问题是我无法插入图片,请告诉我需要以哪种格式插入图片。
我想知道如何将位图保存在数据库中。我已经在数据库中创建了表格:
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,image BLOB)");
}
我的问题是我无法插入图片,请告诉我需要以哪种格式插入图片。
如果您拥有位图图像,则可以执行以下操作。
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);
如果您想这样做,您需要使用 blob。但为什么要这样做呢?我不会将图像存储到数据库中。最好将图像存储在SD卡上,然后将其路径存储到数据库中。通常,数据库安装在手机内存中,这将使手机内存被填满。
将其编写为二进制并存储为BLOB...你走在了正确的道路上。你也可以使用对象来完成它。
http://www.idevelopment.info/data/Programming/java/jdbc/LOBS/BLOBFileExample.java
别忘了 Google 代码:
试试这个
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());