问题
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