安卓无法使用Picasso从URI加载图片

6

这款 Android 应用程序允许用户从手机相册中选择照片,我将其 URI 保存到 Realm 中。然后,我检索此信息并使用 Picasso 将其加载到图像视图中。出于某种原因,图片无法加载。

URI 的格式类似于:

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

我使用 mCategory.icon = imageURI.toString() 将其保存到 Realm,然后在加载时:
Picasso.with(getContext())
                .load(Uri.parse(mCategory.icon)) // mCategory.icon is a string 
                .resize(200, 200)
                .error(R.drawable.mountain) // default image to load
                .into(viewHolder.categoryIcon);

该 Uri 不是有效的图像路径 Uri。 - Enzokie
4个回答

5
您得到的URI是一个ContentProvider URI,如果您想在Picasso中显示它,您可以尝试这样做:
    File file = new File(Uri.parse(mCategory.icon));
    Picasso.with(getContext())
            .load(file)  
            .resize(200, 200)
            .error(R.drawable.mountain) 
            .into(viewHolder.categoryIcon);

附注:虽然您可以将ContentProveder路径转换为Absolute路径,但最好不要这样做,因为Picasso支持从文件加载。


你有检查文件吗?使用file.exists()检查文件是否已正确加载。 - Keivan Esbati
你是如何解决这个问题的?在完成后提供答案是一个良好的举动。 - Cyph3rCod3r
我认为你应该把这个评论发在问题下面,因为这是答案 (^^) - Keivan Esbati

3

在Picasso中使用setLoggingEnabled(true)来检查日志,以查看是否有任何错误消息。


1

这在新版本的Picasso2.71828中完美运行。

Picasso.get()
       .load(imageUri)
       .placeholder(R.drawable.placeholder)
       .fit()
       .centerCrop()
       .into(viewHolder.categoryIcon);

1
这个答案被踩是不正确的。它是解决问题的完美方案。OP没有提到他遇到的Android版本。尽管我相信他意外地尝试了加载contentUri,但自从Android Q以来,因为范围存储概念,只有少数情况允许直接从FileAPI加载。你必须从contentUri加载,这在新的Picasso 2.71828中得到支持——这就是我来这里的原因。所以,谁要迁移到Q并使用Picasso.with().load(file),请使用新的Picasso和Picasso.get().load(contentUri)。谢谢。 - Max Power

0

提到的URI包含冒号:的编码值,即%3A。

要么重命名源文件,要么尝试使用Glide或其他库来实现目的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接