简体   繁体   中英

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()
            }
        })
}

Try this snippet

        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM