[英]android take image from phone album and store it in sqlite database
我正在制作一个应用程序,用户可以从手机的相册中选择图像并将其存储到 sqlite 数据库中的一个表中,我在这里看到很多关于这个问题的帖子,但无法理解解决方案(它们对我也不起作用) ,在我的活动中,我有一个 imageview,单击它会打开相册并允许用户选择图像,而且我还有一个按钮,单击该按钮会将图像存储在 sqlite 数据库中,我只能选择图像但是在那之后我被卡住了,我在我的代码中使用了这个方法:
public void getImage(View view) throws IOException {
ImageView v=(ImageView)view;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent,1);
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContext().getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
现在我应该怎么做才能将图像存储在数据库中?
如果您确定图像不会从内部存储中删除,您可以保存图像路径。 如果要保存图像数据,可以执行以下操作。
用于选择图像
private void selectImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQ);
}
在 onActivityResult 中,来自 Intent 数据...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQ && resultCode == Activity.RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), path);
Bitmap.createScaledBitmap(bitmap, 150, 150, true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
从 bitmap 获取字节 []
public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {
if(bitmap == null) return null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
然后将 byte[] 保存为 sqlite 中的 blob
获取图像为 bitmap
public static Bitmap getBitmapFromByteArray(byte[] blob){
if(blob == null) return null;
Bitmap bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
return bitmap;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.