imageCapture.takePicture - 保存的图像转换为位图

imageCapture.takePicture - saved image convert to Bitmap

我有一个抓图方法:


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

我想从我在 .takePicture 方法中保存的图像中获取位图,我尝试了各种方法,但没有一个像我想要的那样工作

你必须在 onImageSaved() 中调用 ImageView.setImageBitmap() 所以只用这个 :

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

还有这个:

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

您会在这个位置找到您保存的图像:

/storage/emulated/0/Android/data/{com.YourPackgeName}/files/1617841388672.jpg