My onActivityResult
is not working because getBitmap
is deprecated, any alternative codes to achieve this?
here are the codes that needs to
ImageDecoder.createSource(this.getContentResolver(), pictureUri)
works fine, but to be able to use this code, mindSdkVersion should be at least 28.
You can use:
private fun getCapturedImage(selectedPhotoUri: Uri): Bitmap {
val bitmap = when {
Build.VERSION.SDK_INT < 28 -> MediaStore.Images.Media.getBitmap(
this.contentResolver,
selectedPhotoUri
)
else -> {
val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri)
ImageDecoder.decodeBitmap(source)
}
}
Check the official doc:
This method was deprecated in API level 29. loading of images should be performed through ImageDecoder#createSource(ContentResolver, Uri), which offers modern features like PostProcessor.
This worked well for me in java
ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), pictureUri);
Bitmap bitmap = ImageDecoder.decodeBitmap(source);
I have created a class for loading a Bitmap from uri:
public class BitmapResolver {
private final static String TAG = "BitmapResolver";
@SuppressWarnings("deprecation")
private static Bitmap getBitmapLegacy(@NonNull ContentResolver contentResolver, @NonNull Uri fileUri){
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(contentResolver, fileUri);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@TargetApi(Build.VERSION_CODES.P)
private static Bitmap getBitmapImageDecoder(@NonNull ContentResolver contentResolver, @NonNull Uri fileUri){
Bitmap bitmap = null;
try {
bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(contentResolver, fileUri));
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
public static Bitmap getBitmap(@NonNull ContentResolver contentResolver, Uri fileUri){
if (fileUri == null){
Log.i(TAG, "returning null because URI was null");
return null;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
return getBitmapImageDecoder(contentResolver, fileUri);
} else{
return getBitmapLegacy(contentResolver, fileUri);
}
}
}
Just to save you some time ...
This worked for me,
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
val selectedPhotoUri = data.data
try {
selectedPhotoUri?.let {
if(Build.VERSION.SDK_INT < 28) {
val bitmap = MediaStore.Images.Media.getBitmap(
this.contentResolver,
selectedPhotoUri
)
imageView.setImageBitmap(bitmap)
} else {
val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri)
val bitmap = ImageDecoder.decodeBitmap(source)
imageView.setImageBitmap(bitmap)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}