Home > Net >  Convert image from gallery to bitmap. I get a NullPointerException
Convert image from gallery to bitmap. I get a NullPointerException

Time:01-07

I'm trying to convert an image from the gallery into a bitmp and then store it in an array. Previously, however, I am getting a NullPointerException. How can I convert the image from the gallery?

AddNewHomeFragment.kt:

...

else if(requestCode == GALLERY &&  resultCode == Activity.RESULT_OK && data != null)
    {
        //imgData = "content://media/external/images/media/100051...
        val imgData = data.data!!
        val inputStream = requireContext().contentResolver.openInputStream(imgData)

        val exif = ExifInterface(inputStream!!)

        val rotation = exif.getAttributeInt(
            ExifInterface.TAG_ORIENTATION,
            ExifInterface.ORIENTATION_UNDEFINED
        )
        val rotationInDegrees: Int = exifToDegrees(rotation)

        //ERROR THROWS HERE
        val bitmap = BitmapFactory.decodeStream(inputStream)

        val bitmapReturn = rotateBitmap(bitmap,rotationInDegrees)
        listImg[aktuellesBild] = bitmapReturn!!

        adapter.notifyItemChanged(aktuellesBild)
    }

Caused by: java.lang.NullPointerException: bitmap must not be null

CodePudding user response:

You cannot reuse inputStream. ExifInterface will have consumed the stream already. You need to call openInputStream() again to get a fresh InputStream to pass to BitmapFactory.decodeStream().

  • Related