通过Android Media Store将图像存储在新文件夹中

时间:2020-03-22 11:33:02

标签: android image gallery mediastore

我正在使用以下内容将在我的应用中创建的图像存储在Android画廊中:

    MediaStore.Images.Media.insertImage(contentResolver, bitmap, "SomeTitle", "Description");

这会将图像存储在Picture-Device-Folder中,并将它们添加到Gallery中。

我现在想为我的应用程序创建一个特定的图像文件夹,以便将图像存储在文件夹“ MyApp”而不是“ Picture”中。我该怎么办?

1 个答案:

答案 0 :(得分:6)

我找到了隐藏在这里的解决方案:https://stackoverflow.com/a/57265702/289782

我要在此引用它,因为原始问题还很老,而包雷网友的好答案排名很低。

在API 29(Android Q)之前有几种不同的实现方法,但所有方法都涉及一个或几个Q不推荐使用的API。在2019年,这是一种实现向后和向前兼容的方法:

(由于是2019年,所以我将用Kotlin写作)

/// @param folderName can be your app's name
private fun saveImage(bitmap: Bitmap, context: Context, folderName: String) {
    if (android.os.Build.VERSION.SDK_INT >= 29) {
        val values = contentValues()
        values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + folderName)
        values.put(MediaStore.Images.Media.IS_PENDING, true)
        // RELATIVE_PATH and IS_PENDING are introduced in API 29.

        val uri: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        if (uri != null) {
            saveImageToStream(bitmap, context.contentResolver.openOutputStream(uri))
            values.put(MediaStore.Images.Media.IS_PENDING, false)
            context.contentResolver.update(uri, values, null, null)
        }
    } else {
        val directory = File(Environment.getExternalStorageDirectory().toString() + separator + folderName)
        // getExternalStorageDirectory is deprecated in API 29

        if (!directory.exists()) {
            directory.mkdirs()
        }
        val fileName = System.currentTimeMillis().toString() + ".png"
        val file = File(directory, fileName)
        saveImageToStream(bitmap, FileOutputStream(file))
        if (file.absolutePath != null) {
            val values = contentValues()
            values.put(MediaStore.Images.Media.DATA, file.absolutePath)
            // .DATA is deprecated in API 29
            context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        }
    }
}

private fun contentValues() : ContentValues {
    val values = ContentValues()
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/png")
    values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
    return values
}

private fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?) {
    if (outputStream != null) {
        try {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
            outputStream.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

此外,在调用此功能之前,您需要先拥有WRITE_EXTERNAL_STORAGE。