首页 > 解决方案 > 无法保存图像并在我的画廊中查看

问题描述

我有一个要保存并显示在我的画廊中的位图图像,不幸的是,我在尝试完成此任务时遇到了很多问题。从昨天开始,我可能已经尝试了十几个不同的代码片段来做到这一点。我认为正在发生的事情是这些代码片段正在工作,但它们将其保存在应用程序的数据中,而不是共享存储/库中。

如何重新调整此代码以使其将图像存储在任何图库应用程序或文件管理器都可以访问的文件夹中,而不仅仅是在应用程序的数据中?

private fun saveToGallery(bitmap: Bitmap) {

        Toast.makeText(applicationContext,"Saving image!", Toast.LENGTH_SHORT).show()
        var outputStream: FileOutputStream? = null
        val file = Environment.getExternalStorageDirectory()
        val dir = File(file.absolutePath.toString() + "/MyPics")
        dir.mkdirs()
        val filename = String.format("%d.png", System.currentTimeMillis())
        val outFile = File(dir, filename)
        try {
            outputStream = FileOutputStream(outFile)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        try {
            outputStream!!.flush()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            outputStream!!.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

标签: androidkotlin

解决方案


您应该在保存图像后发送广播事件。

例如: https ://stackoverflow.com/a/39448816/5313283


推荐阅读