1

I have a capture image method:


fun captureImage() {
        val dialog = AlertDialog.Builder(this)
            .setMessage("Saving picture...")
            .setCancelable(false)
            .show()

        val file = File(
                getExternalFilesDir(null)?.absolutePath,
                System.currentTimeMillis().toString() + ".jpg"
        )
        file.createNewFile()

        var image_bitmap: Bitmap? = null

        val outputFileOptions = ImageCapture.OutputFileOptions.Builder(file).build()
        imageCapture.takePicture(outputFileOptions,
                Executors.newSingleThreadExecutor(),
                object : ImageCapture.OnImageSavedCallback {
                    override fun onImageSaved(output: ImageCapture.OutputFileResults) {

   //here I tried different things

                        runOnUiThread {
                            dialog.dismiss()
                            Toast.makeText(this@MainActivity, "Image saved!", Toast.LENGTH_LONG).show()
                        }
                    }

                    override fun onError(exception: ImageCaptureException) {
                        runOnUiThread {
                            dialog.dismiss()
                            Toast.makeText(this@MainActivity, exception.message, Toast.LENGTH_LONG)
                                    .show()
                        }
                    }
                })

        findViewById<ImageView>(R.id.image_view).setImageBitmap(image_bitmap)
    }

and I want to get a bitmap from the image I saved in the .takePicture method, I tried various things but non of them worked like I wanted it

1 Answers1

1

You must call the ImageView.setImageBitmap() inside the onImageSaved() so just use this :

 override fun onImageSaved(output: ImageCapture.OutputFileResults) {

                //here I tried different things
                runOnUiThread {
                      val bitmap: Bitmap = BitmapFactory.decodeFile(file.path)
                      findViewById<ImageView>(R.id.image_view).setImageBitmap(bitmap)
                      dialog.dismiss()
                      Toast.makeText(this@MainActivity, "Image saved!", Toast.LENGTH_LONG).show()
                 }
           }

Also with this :

val file = File( getExternalFilesDir(null)?.absolutePath, System.currentTimeMillis().toString() + ".jpg" )

you will find you saved image in this location :

/storage/emulated/0/Android/data/{com.YourPackgeName}/files/1617841388672.jpg
Shay Kin
  • 2,539
  • 3
  • 15
  • 22
  • 1
    And if I want to use the picture for later use? Cause if I try to save it in a global variable inside the onImageSaved() and I try to use it later it says it's null –  Apr 08 '21 at 09:56
  • 1
    Yes its null please check this [Answer](https://stackoverflow.com/a/60583790/7085389) – Shay Kin Apr 08 '21 at 20:05