Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deprecated "getBitmap" with API 29. Any alternative codes?

My onActivityResult is not working because getBitmap is deprecated, any alternative codes to achieve this?

here are the codes that needs to be changed, any suggestions?

val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)

the getBitmap is crossed and says its deprecated

like image 342
jaedster medina Avatar asked Jun 18 '19 14:06

jaedster medina


4 Answers

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()
            }
        }
    }
like image 101
Ally Avatar answered Nov 04 '22 21:11

Ally


This worked well for me in java

ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), pictureUri);
Bitmap bitmap = ImageDecoder.decodeBitmap(source);
like image 23
davincia Avatar answered Nov 04 '22 22:11

davincia


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)
            }
        }
like image 17
Hasan A Yousef Avatar answered Nov 04 '22 23:11

Hasan A Yousef


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.

like image 8
Gabriele Mariotti Avatar answered Nov 04 '22 21:11

Gabriele Mariotti