首先,要将图片转换为字节数组,然后将字节数组存储在数据库中。如果简单地将图片的路径存储在数据库中,则会出现上述问题。以下是示例代码,该示例代码使用Base64编码将字节数组转换为字符串:
// 将图片转换为字节数组
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// 将字节数组转换为Base64字符串
String imageString = Base64.encodeToString(byteArray, Base64.DEFAULT);
// 将Base64字符串存储在数据库中
ContentValues values = new ContentValues();
values.put("image", imageString);
db.insert("table_name", null, values);
在从数据库中检索图像时,可以使用以下示例代码将Base64字符串转换回字节数组:
// 获取Base64字符串
String imageString = cursor.getString(cursor.getColumnIndex("image"));
// 将Base64字符串转换为字节数组
byte[] byteArray = Base64.decode(imageString, Base64.DEFAULT);
// 使用字节数组创建位图
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);