如何在Android Q中将文件从特定于应用程序的文件夹(文件://方案)复制到MediaStore Images集合(内容://方案)?

由Liskovych

我正在尝试使用以下方法将文件从特定于应用程序的文件夹复制到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)

}

结果图像无法打开。我究竟做错了什么?

blackapps
length = inputStream.read(buffer) 

删除该语句。

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

因此,新文件缺少“标头”。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章