[英]Adding an Image to a sqlite database
我已经为此苦苦挣扎了一段时间,我希望能够将图像存储到我的数据库中。 我知道将图像直接存储到数据库是一种不好的做法,但我只是不知道如何用另一种方式来做。
所以,我目前遇到了一些问题。
首先,我什至不确定我的路径是否正确; 我想获取一个可绘制文件并将其存储到我的数据库中,并且必须有一种比直接从 C 驱动器创建路径更简单的方法,对吧?
其次,我对此了解不多,但我需要将我的文件转换为位图,以便它可以转换为字节数组? 而且我不确定该怎么做。
我已经尝试了几件事,已经以不同的方式将这段代码写了大约 10 次,但一无所获。 提前感谢大家的帮助。
public void insertAvatar(String Email, byte[] head) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String sql = "INSERT INTO Avatar VALUES (?, ?)";
File head = new File("C:\\Users\\PC\\Desktop\\capaa\\src\\main\\res\\drawable\\head2.png");
Bitmap imageToStoreBitmap = head; // doesn't work as my file isnt a bitmap yet
objectByteArrayOutputStream = new ByteArrayOutputStream();
imageToStoreBitmap.compress(Bitmap.CompressFormat.JPEG, 100, objectByteArrayOutputStream);
imageInBytes = objectByteArrayOutputStream.toByteArray();
contentValues.put("Email", Email);
contentValues.put("head", imageInBytes);
long checkIfQueryRuns = db.insert("Avatar", null, contentValues );
}
您需要使用 Blob 将图像存储在 SQLite 数据库中。
创建一个表来存储图像
CREATE TABLE " + DB_TABLE_NAME + "("+
KEY_NAME + " TEXT," +
KEY_IMAGE + " BLOB);";
将图像存储在表中
public void addImage( String name, byte[] image) throws SQLiteException{
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE_NAME, null, cv );
}
如您所见,在将图像插入表格之前,您需要将位图转换为字节数组。
// To convert from bitmap to byte array
public static byte[] getImageBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
从数据库中检索图像
//search your image using the key and get the cursor
............
byte[] image = cursor.getBlob(1);
............
如您所见,返回的图像位于字节数组中。 现在您可以将此字节数组转换为位图以在您的应用程序中使用。
//To convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
写完答案后,我本人不太喜欢将图像存储在数据库中。 我不确定你需要什么来存储图像,但你可以检查以下库来处理你的应用程序中的图像。
https://github.com/bumptech/glide/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.