Android Q 如何将文件从应用程序特定文件夹(file:// scheme)复制到 MediaStore Images collection(content:// scheme)?

How to copy file from app-specific folder (file:// scheme) to MediaStore Images collection (content:// scheme) in Android Q?

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

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

}

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

length = inputStream.read(buffer) 

删除该语句。

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

因此新文件缺少 'header'。

新文件更短。但是您没有比较文件大小。 –