【问题标题】:how to save image to gallery in kotlin如何将图像保存到kotlin中的画廊
【发布时间】:2021-10-09 13:51:36
【问题描述】:

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

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/*")


    }

【问题讨论】:

  • I used this code below to add the image and it's worked but I don't know how to save the image 添加什么?你为什么要一开始就复印?如果用户可以选择它,它已经在您的设备上并且“在图库中”。
  • 设置成Imageview后不用再保存
  • @blackapps 我稍后会添加一些按钮来编辑图像,然后我会保存它,所以我想知道如何保存图像,我希望你明白我想要做什么跨度>
  • 如果你编辑了一个“图像”,我不知道你有什么,因此我不知道你想保存什么。

标签: android image android-studio kotlin save


【解决方案1】:

//使用下面的代码将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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    相关资源
    最近更新 更多