【问题标题】:Loading image into ImageView using Glide with Uri returned from intent with action as ACTION_GET_CONTENT使用 Glide 将图像加载到 ImageView 中,Uri 从意图返回,动作为 ACTION_GET_CONTENT
【发布时间】:2018-02-26 11:45:59
【问题描述】:

我正在尝试使用 Glide 库在 ImageView 中显示图像。我正在使用在OnActivityResult 中返回的 Uri(Intent.getData()) 在ImageView 中显示。我打算按如下方式选择图像:

Intent intent = new Intent();

    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select an image"),77);

那么 OnActivityResult 返回的 Uri 是这样的:

content://com.android.providers.media.documents/document/image%3A21300

在 OnActivityResult 我做了以下事情,但 Image 没有显示在 ImageView 中:

Uri uri = data.getData();
Log.e("uri", uri.toString());            
addedImageView.setVisibility(View.VISIBLE);
GlideApp.with(this).load(uri).placeholder(new ColorDrawable(Color.RED)).into(addedImageView);

到目前为止,我只看到有人使用带有 'file://' 前缀的 Uri,但从未见过 'content://' 前缀。如何使用 Glide 的 'content://' uri 将 Image 加载到 ImageView 中?

【问题讨论】:

标签: android imageview android-glide


【解决方案1】:

确保你已经添加了

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

进入您的清单,如果您的 targetSdk >= 23,您还执行了运行时权限检查。

此外,尝试使用 Uri 中的 File 实例并加载该实例

GlideApp.with(this).load(new File(uri.getPath())).placeholder(new ColorDrawable(Color.RED)).into(addedImageView);

【讨论】:

  • 我已经拥有该权限,并且收到的 uri 不是文件前缀,而是内容前缀。所以它没有用。
  • 其他解决方案可以是从路径获取位图,然后在 ImageView 上设置它以获取更多信息,请查看 [link]hmkcode.com/android-display-selected-image-and-its-real-path
  • 我知道我可以得到位图,但这会导致堆填得太多。这就是我想使用 Glide 的原因。
【解决方案2】:

content 路径转换为 ​​文件 路径, 使用这个功能,

public String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = context.getContentResolver().query(contentURI, null,
            null, null, null);

    if (cursor == null) { // Source is Dropbox or other similar local file
        // path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        try {
            int idx = cursor
                    .getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
        } catch (Exception e) {
            AppLog.handleException(ImageHelper.class.getName(), e);
              result = "";
        }
        cursor.close();
    }
    return result;
}

【讨论】:

  • 我收到如下错误:CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 6 columns.
猜你喜欢
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
相关资源
最近更新 更多