android - 如何在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)
}
生成的图像无法打开。我究竟做错了什么?
解决方案
length = inputStream.read(buffer)
删除该声明。
您正在读取大量字节,但没有将它们写入新文件。
所以新文件错过了“标题”。
新文件更短。但是您没有比较文件大小。——</p>
推荐阅读
- java - 如何将 Date 参数传递给注释,然后在 junit 5 扩展中验证它?
- r - 循环回归:创建交互项,存储结果,只提取有意义的项
- youtube-api - 生成新的刷新令牌后 YouTube API v3 无效授权
- mysql - 在从 Dockerfile 构建期间部署 mysql
- angularjs - 如何在 chrome for Android App 上进行测试和调试
- powershell - PowerShell替换文件中的值
- firebase - 如何从 Flutter 应用程序在 Cloud Firestore 中记录带有嵌套数组的 json
- java - 面临的问题 - SpringBoot 应用程序中的 Olingo OData 4.0 Java 库集成
- sql - 2 个相关的案例陈述
- datetime - 谷歌表格转换错误的日期