Search code examples
android-studioandroid-intentkotlinandroid-bitmapkotlin-extension

captured and displayed image on imageView, now i want to pass the imageView to another activity


This is my code on android studio using kotlin to capture and show image on main activity, I want that captured image to be displayed on my other activity. After image has been captured, the image will be displayed on the imageView on main Activity, now i want to pass that image to another activity using buttonClassify

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

Solution

  • If you store the image in a file, you can just pass the path to the file. If not, you can pass the Bitmap as a Parcelable in the Intent Extras.

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

    Then in the next Activity you could retreive it like this:

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

    Beware, large bitmaps can throw Exceptions when trying to be passed as Intent Extras, so consider saving the image and passing around the path.