【发布时间】:2020-12-18 11:09:12
【问题描述】:
我正在尝试从图库中获取图像并首先从 URI 将其转换为位图,然后将其转换为字节数组,然后尝试将其存储到 BLOB 数据类型列的数据库中。插入查询返回成功消息但不反映到数据库中。但是当我将空字节数组传递给它时,它会存储整行。
Bitmap 到 byte[] 的代码:
byte[] imgByteArray;
int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
imgByteArray = byteBuffer.array();
更新:
从图库和字节转换中获取图像并存储到数据库中的代码:
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_PICTURE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_PICTURE) {
if (data.getData() != null) {
Uri uri = data.getData();
try {
pictureBitmap = getBitmapFromUri(uri);
byte[] imgByteArray;
int size = pictureBitmap.getRowBytes() * pictureBitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
pictureBitmap.copyPixelsToBuffer(byteBuffer);
imgByteArray = byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public boolean insertPicture(byte[] picture, String desc){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cValues = new ContentValues();
cValues.put(KEY_PICTURE, picture);
cValues.put(KEY_DESC, desc);
long rowId = db.insert(PICTURE_TABLE,null, cValues);
Log.d("TAG","Row ID : "+rowId);
db.close();
if(rowId!=0){
return true;
}else {
return false;
}
}
【问题讨论】:
-
请提供您用于从图库中获取图像、将此图像存储到数据库以及从数据库中检索它的代码
-
我已经用代码更新了这个问题。请看一下。谢谢
-
trying to get image from gallery and convert it into Bitmap first这看起来是个坏主意。特别是因为您想在保存之前将其所有像素放入一个数组中。这将花费您大量的存储空间。与您刚刚存储所选 jpg 文件时相比,可能要多 20 倍。 -
@blackapps 哦,我不知道这个。那么从您的角度来看,为了更好地管理内存,实现这一目标的最佳方法是什么?
-
我已经告诉过你了:存储所选 jpg 文件本身的字节数。不要使用中间位图。
标签: android android-studio android-sqlite