首页 > 解决方案 > 如何将图像保存到kotlin中的画廊

问题描述

我正在开发一个从用户图库添加图像然后再次保存的项目,我使用下面的代码让用户选择图像并将其添加到应用程序中并且它有效但我不知道如何保存图像(稍后我将添加将编辑图像的按钮,所以我想知道如何在编辑后保存它)

lateinit var photo: ImageView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)


    photo = findViewById<ImageView>(R.id.photo);
    val upload = findViewById<Button>(R.id.upload)


    val getaction = registerForActivityResult(
        ActivityResultContracts.GetContent(),
        ActivityResultCallback { uri ->
            photo.setImageURI(uri)
        }
    )

    upload.setOnClickListener {
        getaction.launch("image/*")


    }

标签: androidimageandroid-studiokotlinsave

解决方案


//使用下面的代码将uri保存到位图:

        //Create a bitmap using the uri from your code
     Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));

// 获得位图后,您可以将其保存到存储中,请记住您可能需要权限,具体取决于您要保存图像的位置。

//Code to save bitmap to image on storage, filePath will be the path you wish to save it to.

    try {
    File file = new File(filePath);
    FileOutputStream fOut = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
}
catch (Exception e) {
    e.printStackTrace();
    LOG.i(null, "Save file error!");
    return false;
}

推荐阅读