Transfer image to other activity in kotlin

半世苍凉 提交于 2020-12-15 07:19:36

问题


I am making an application like instagram which will allow the user to upload their pic and if they need any editing then they can press editing button and they can edit. How can I transfer the same photo which the user chose to the editing activity in kotlin? And also after editing how can I covert the whole ConstraintLayout to image and transfer it back to the upload activity.


回答1:


You can save the image to internal storage from activity one, then send the image name to the second activity (via Intent) and open it in second activity.

  1. Save the image to internal storage:

    saveToInternalStorage(context, <your_bitmap>, <image_name>)

  2. Start activity like in this link and instead of message put <image_name>

  3. On opened activity, get your <image_name>

  4. Open the image from internal storage:

    val bitmap = getImageFromInternalStorage(context, <image_name>)

Here is my storage helper class:

class ImageStorageManager {
    companion object {
        fun saveToInternalStorage(context: Context, bitmapImage: Bitmap, imageFileName: String): String {
            context.openFileOutput(imageFileName, Context.MODE_PRIVATE).use { fos ->
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 50, fos)
            }
            return context.filesDir.absolutePath
        }

        fun getImageFromInternalStorage(context: Context, imageFileName: String): Bitmap? {
            val directory = context.filesDir
            val file = File(directory, imageFileName)
            return if (file.exists()) {
                BitmapFactory.decodeStream(FileInputStream(file))
            } else {
                null
            }
        }

        fun deleteImageFromInternalStorage(context: Context, imageFileName: String): Boolean {
            val dir = context.filesDir
            val file = File(dir, imageFileName)
            return file.delete()
        }
    }
}


来源:https://stackoverflow.com/questions/62671532/transfer-image-to-other-activity-in-kotlin

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