首页 > 解决方案 > 如何在Android Q中将文件从应用程序特定文件夹(file://方案)复制到MediaStore图像集合(content://方案)?

问题描述

我正在尝试使用此方法将文件从特定于应用程序的文件夹复制到 MediaStore 图像集合:

/**
 * Copies file from path of scheme `file://` to Uri of scheme `content://`
 *
 * @param fromPath Example: /storage/emulated/0/com.my.package/FILE/7225832726757260/wang-shaohong-Kh-NfgSYqN0-unsplash.jpg
 * @param toContentUri should be of `content://` scheme. Example: content://media/external_primary/downloads/1515
 */
@Throws(IOException::class)
fun copyFilePathToContentUri(fromPath: String, toContentUri: Uri) {
    AppContext.getAppContext().contentResolver.openOutputStream(toContentUri)?.use { outputStream ->
        FileInputStream(fromPath).use { inputStream ->
            val buffer = ByteArray(1024)
            var length: Int
            length = inputStream.read(buffer)

            while (inputStream.read(buffer).also { length = it } > 0) {
                outputStream.write(buffer, 0, length)
            }
        }
    }
}

内容 uri 使用以下方法创建:

fun createImagesFile(imagePath: String): Uri? {
    val fileExtension = imagePath.substringAfterLast('.', "")
    if (fileExtension.isBlank()) return null
    val map = MimeTypeMap.getSingleton()
    val mimeType = map.getMimeTypeFromExtension(fileExtension) ?: return null
    if (!mimeType.startsWith("image/")) {
        loge("FileUtils createImagesFile Error. Given file is not of image type")
        return null
    }

    val volumeName = if (hasAndroid10()) MediaStore.VOLUME_EXTERNAL_PRIMARY else MediaStore.VOLUME_EXTERNAL

    val values = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, "Photo")
        put(MediaStore.Images.Media.MIME_TYPE, mimeType)
        if (hasAndroid10()) {
            put(MediaStore.Images.Media.IS_PENDING, 1)
        }
    }
    val collection = MediaStore.Images.Media.getContentUri(volumeName)

    return Application.getAppContext().contentResolver.insert(collection, values)

}

生成的图像无法打开。我究竟做错了什么?

标签: androidkotlinmediastoreandroid-10.0scoped-storage

解决方案


length = inputStream.read(buffer) 

删除该声明。

您正在读取大量字节,但没有将它们写入新文件。

所以新文件错过了“标题”。

新文件更短。但是您没有比较文件大小。——</p>


推荐阅读