在imageView上捕获并显示图像,现在我想将imageView传递给另一个活动

时间:2018-11-24 13:44:21

标签: android-studio android-intent kotlin android-bitmap kotlin-extension

这是我在Android Studio上使用kotlin捕获并显示主要活动图像的代码,我希望捕获的图像显示在其他活动中。捕获图像后,该图像将显示在主Activity的imageView上,现在我想使用buttonClassify将该图像传递给另一个Activity

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    initializeTensorClassifier()
    buttonRecognize.setOnClickListener {
        setVisibilityOnCaptured(false)
        cameraView.captureImage {
            onImageCaptured(it)
        }
     buttonClassify.setOnClickListener{
         val intent = Intent(this, classify::class.java)

         startActivity(intent)
     }
    }
}

private fun onImageCaptured(it: CameraKitImage) {
    val bitmap = Bitmap.createScaledBitmap(it.bitmap, INPUT_WIDTH, INPUT_HEIGHT, false)
    showCapturedImage(bitmap)

    classifier?.let {
        try {
            showRecognizedResult(it.recognizeImage(bitmap))
        } catch (e: java.lang.RuntimeException) {
            Log.e(TAG, "Crashing due to classification.closed() before the recognizer finishes!")
        }
    }
}



private fun showCapturedImage(bitmap: Bitmap?) {
    runOnUiThread {
        imageCaptured.visibility = View.VISIBLE
        imageCaptured.setImageBitmap(bitmap)
    }
}

1 个答案:

答案 0 :(得分:0)

如果将图像存储在文件中,则只需将路径传递到文件。如果没有,您可以在Bitmap Extras中将Parcelable作为Intent传递。

private fun showCapturedImage(bitmap: Bitmap?) {
    runOnUiThread {
        imageCaptured.visibility = View.VISIBLE
        imageCaptured.setImageBitmap(bitmap)

        val nextActivityIntent = Intent(this, NextActivity::class.java).apply {
            putExtra("captured_image", bitmap)
        }

        startActivity(nextActivityIntent)
    }
}

然后在下一个活动中,您可以像这样恢复它:

override fun onCreate(savedInstance: Bundle?) {
    ...
    val capturedImage = intent.extras.getParcelable("captured_image") as Bitmap?
    /* Use bitmap as you wish */
}

当心,大型位图在尝试作为Intent Extras传递时可能会引发 Exceptions ,因此请考虑保存图像并在路径周围传递。