There are some answers using java in stackoverflow but i am unable to convert it into kotlin code. I am new to kotlin. Please tell me how to transfer bitmap data from one activity to another using Intent
            Asked
            
        
        
            Active
            
        
            Viewed 879 times
        
    2 Answers
2
            
            
        I won't recommend you to pass Bitmap as Parcelable as it may lead to memory and performance issues based on the size of the image.
I would suggest you save the bitmap in a file named "yourimage" in the internal storage of your application which is not accessible by other apps.
Saving the bitmap method
fun createImageFromBitmap(bitmap: Bitmap): String? {
    var fileName: String? = "myImage" //no .png or .jpg needed
    try {
        val bytes = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
        val fo: FileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE)
        fo.write(bytes.toByteArray())
        // remember close file output
        fo.close()
    } catch (e: Exception) {
        e.printStackTrace()
        fileName = null
    }
    return fileName
}
At the receiving activity, get the image to Bitmap variable
val bitmap = BitmapFactory.decodeStream(
            context
                .openFileInput("yourimage")
        )
 
    
    
        Shalu T D
        
- 3,921
- 2
- 26
- 37
- 
                    OP asked for passing it through Intents but yes, this is particularly a better solution for bitmaps. +1 – Quanta Jun 22 '20 at 16:43
1
            You need to pass the bitmap as an extra argument to the intent while starting the activity.
val intent = new Intent(this, NewActivity::class.java)
intent.putExtra("BitmapImage", bitmap)
startActivity(intent);
and retrieve it as:
val bitmap = this.intent?.getParcelableExtra("BitmapImage") as Bitmap
I simply translated the code Here to kotlin. You should use Android Studio to translate Java code to Kotlin.
 
    
    
        Quanta
        
- 594
- 3
- 24
