How to get a Bitmap object from an Uri (if I succeed to store it in
/data/data/MYFOLDER/myimage.png
or file///data/data/MYFOLDER/myimage.png
) to u
It seems that MediaStore.Images.Media.getBitmap
was deprecated in API 29
. The recommended way is to use ImageDecoder.createSource
which was added in API 28
.
Here's how getting the bitmap would be done:
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(requireContext().contentResolver, imageUri))
} else {
MediaStore.Images.Media.getBitmap(requireContext().contentResolver, imageUri)
}
private void uriToBitmap(Uri selectedFileUri) {
try {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(selectedFileUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This is the easiest solution:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
(KOTLIN) So, as of April 7th, 2020 none of the above mentioned options worked, but here's what worked for me:
If you want to store the bitmap in a val and set an imageView with it, use this:
val bitmap = BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }
If you just want to set the bitmap to and imageView, use this:
BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }
Uri imgUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imgUri);
you can do this structure:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
Bundle extras = imageReturnedIntent.getExtras();
bitmap = extras.getParcelable("data");
}
break;
}
by this you can easily convert a uri to bitmap. hope help u.