Edita Komarova
Edita Komarova

Reputation: 403

Kotlin: How to convert image uri to bitmap

Most of the answers are in Java I manage to find this solution in Kotlin but it didn't work for me. I also tried finding documentation but I couldn't find one What I'm trying to do is to select photo from gallery and then I want to convert Uri to Bitmap and then save it to the Room Database.

I would like to have a code similar to that but in Kotlin

Uri imageUri = intent.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
Imageview my_img_view = (Imageview ) findViewById (R.id.my_img_view);
my_img_view.setImageBitmap(bitmap

Upvotes: 6

Views: 11683

Answers (3)

GeneCode
GeneCode

Reputation: 7588

Java equivalent:

Uri imageUri = result.getData().getData();
ImageDecoder.Source s = ImageDecoder.createSource(this.getContentResolver(), imageUri);
Bitmap bm = ImageDecoder.decodeBitmap(s);
imageView.setImageBitmap(bm);

I use this code inside registerForActivityResult.

Upvotes: 0

MiStr
MiStr

Reputation: 1223

As of Oct 2022:

Since MediaStore.Images.Media.getBitmap is deprecated, here is another option (from within a Fragment):

val imageUri: Uri = intent.data
val source = ImageDecoder.createSource(requireActivity().contentResolver, imageUri)
val bitmap = ImageDecoder.decodeBitmap(source)
val my_img_view = findViewById(R.id.my_img_view) as Imageview 
my_img_view.setImageBitmap(bitmap)

Upvotes: 4

Hascher
Hascher

Reputation: 566

Use this:

val imageUri: Uri = intent.data;
val bitmap: Bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver(), Uri.parse(imageUri))
val my_img_view = findViewById(R.id.my_img_view) as Imageview 
my_img_view.setImageBitmap(bitmap)

Upvotes: 6

Related Questions