transfer bitmap between two activities in Kotlin

五迷三道 提交于 2020-07-23 06:54:06

问题


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


回答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.




回答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")
        )


来源:https://stackoverflow.com/questions/62488228/transfer-bitmap-between-two-activities-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!