'How to get Bitmap From imageUri in Api level 30?
I am using getBitmap method in the older version but I can't find any alternative of getBitmap From Uri.
try {
bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri);
} catch (IOException e) {
e.printStackTrace();
}
now I found another method from the android guide but still, this is not working. I Don't how to perform this method in the worker thread. Guide says that this method should run in a worker thread. can anyone help me with how to do this?
try {
bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(contentResolver, imageUri));
} catch (IOException e) {
e.printStackTrace();
}
I had created simple class to get bitmap from imageUri. here it is.
public class 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){
return null;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
return getBitmapImageDecoder(contentResolver, fileUri);
} else{
return getBitmapLegacy(contentResolver, fileUri);
}
}
}
Solution 1:[1]
Have a look at the documentation
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.
So you have to make use of ImageDecoder.createSource
, like this:
Bitmap bitmap = null;
ContentResolver contentResolver = getContentResolver();
try {
if(Build.VERSION.SDK_INT < 28) {
bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri);
} else {
ImageDecoder.Source source = ImageDecoder.createSource(contentResolver, imageUri);
bitmap = ImageDecoder.decodeBitmap(source);
}
} catch (Exception e) {
e.printStackTrace();
}
The above should be thread-safe.
Solution 2:[2]
Here it For Kotlin Developers
fun getBitmap(contentResolver: ContentResolver, fileUri: Uri?): Bitmap? {
return try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(contentResolver, fileUri!!))
} else {
MediaStore.Images.Media.getBitmap(contentResolver, fileUri)
}
} catch (e: Exception){
null
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | HB. |
Solution 2 | Rahul Tala |