【问题标题】:How can I pass an image file if I have the image's content uri?如果我有图像的内容 uri,如何传递图像文件?
【发布时间】:2019-04-17 07:13:53
【问题描述】:

我想使用调整大小的库来压缩一些照片。该库要求我将源文件传递给它。我以简单的意图选择图像,我得到的回报是像这样的内容 Uri:

content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F96/ORIGINAL/NONE/2013194373

但是当我将它放在 File() 中时,它会崩溃并出现以下错误 Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference

如何将此内容 uri 转换为文件功能的有效路径? 我尝试过以不同的方式使用 Uri.parse,但无法弄清楚。

我也试图弄乱内容解析器,但不明白如何让它工作。

如果可能的话,我非常感谢 Kotlin 的帮助,但也可能会在 Java 中理解它。

【问题讨论】:

  • 您无法将 Uri 转换为 File - 但是您可以将其“转换”为 InputStream - 请再次参阅 ContentResolver 文档了解更多信息
  • 我已经能够像val myInputStream = activity!!.contentResolver.openInputStream(Uri.parse(localImagePost.imageUri)) 这样获得输入流,但我找不到可以将其转换为文件路径的方法
  • 你无法获取任何“文件路径”,你需要它做什么?
  • 我正在使用图像选择器供用户选择图像。然后在上传之前调整该图像的大小,但我用来调整它大小的代码需要我将文件传递给它。我在拍照并立即调整大小时成功使用了代码,但那是因为我持有新文件。
  • here 他们正在使用 BitmapFactory.decodeFile() 方法 - 只需将其更改为 BitmapFactory.decodeStream() - 这样您就不需要创建任何临时文件,使用 FileUtils.copyInputStreamToFile() 复制内容然后删除它

标签: android image file kotlin uri


【解决方案1】:

我之前找到了这个(我不记得在哪里)

private fun getRealPathFromUri(context: Context, contentUri: Uri): String {
    var cursor: Cursor? = null
    try {
        val proj = arrayOf(MediaStore.Images.Media.DATA)
        cursor = context.contentResolver.query(contentUri, proj, null, null, null)
        val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor.moveToFirst()
        return cursor.getString(columnIndex)
    } finally {
        if (cursor != null) {
            cursor.close()
        }
    }
}

这样称呼

val file = File(getRealPathFromUri(context, uri))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多