Search code examples
androidkotlinuriandroid-bitmapandroid-image

Convert Uri to Bitmap


I want to convert a Uri from the .takePicture method to a Bitmap for later use, I searched for different methods but each gaved me an error saying that the bitmap is null and sometimes "int android.graphics.bitmap.getwidth()' on a null object reference".


var imageUri:Uri?=null
    private fun takePhoto() {

        val photofile = File(externalMediaDirs.firstOrNull(), "picture - ${System.currentTimeMillis()}.jpg")
        val output = ImageCapture.OutputFileOptions.Builder(photofile).build()
        var image_View = findViewById<ImageView>(R.id.imageView)

        imageCapture?.takePicture(output, ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageSavedCallback {
            override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                Toast.makeText(applicationContext, "Pic saved.", Toast.LENGTH_LONG).show()
                imageUri = outputFileResults.savedUri
                //image_View.setImageURI(imageUri)
            }

            override fun onError(exception: ImageCaptureException) {
                Toast.makeText(applicationContext, "Error saving pic!", Toast.LENGTH_LONG).show()
            }
        })
}

Solution

  • Quoting the documentation for getSavedUri():

    This field is only returned if the ImageCapture.OutputFileOptions is backed by MediaStore constructed with #Builder(ContentResolver, Uri, ContentValues)

    That is not the constructor that you are using for OutputFileOptions. So, check to see if getSavedUri() is returning null. If it is, you will need to use photofile, including taking steps to save that in the saved instance state Bundle.

    If getSavedUri() is returning a non-null value, you might want to edit your question and supply the complete stack trace associated with your crash (rather than using a pastebin).