【问题标题】:Android Picasso - Save image locally before viewing it in ImageViewAndroid Picasso - 在 ImageView 中查看之前将图像保存在本地
【发布时间】:2016-09-01 04:30:57
【问题描述】:

我制作了一个显示图像列表的应用程序。但在此之前,我将所有图像下载到 sdcard,并显示一个包含下载文件数量的进度对话框。由于要下载许多图像,我正在考虑使用 Picasso 优化该过程。所以没有进度对话框。使用毕加索,我想在图像显示在 ImageView 之前将图像保存在我的应用程序目录中(作为正常下载的文件)。我想使用这段代码:

Picasso picassoInstance = new Picasso.Builder(context)
 .downloader(new CustomDownloader(context, destination))
 .build();

自定义下载器:

public class CustomDownloader extends OkHttpDownloader {

    private File destination;

    public CustomDownloader(Context context, File destination){
        super(context);
        this.destination = destination;
    }

    @Override
    public Response load(Uri uri, boolean localCacheOnly) throws IOException {
        Response response = super.load(uri, networkPolicy);

        FileOutputStream fileOutput = new FileOutputStream(destination);
        InputStream inputStream = response.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return response;
    }
}

最后,我使用这个语句在 ImageView 中加载图像:

picassoInstance.load(item.getItem().getPath()).resize(width,0).into(imageView);

我使用这种实现是否正确?或者你能提供另一种方式吗?

编辑 1:我使用上面的代码,但图像未显示在 ImageView 中,即使我看到 SDCARD 中下载的图像。

编辑 2:使用此代码,使用新线程:

@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
    Response response = super.load(uri, networkPolicy);
    new Thread(new Runnable() {
        try {
            FileOutputStream fileOutput = new FileOutputStream(destination);
            InputStream inputStream = response.getInputStream();

            byte[] buffer = new byte[1024];
            int bufferLength;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
            }
            fileOutput.close();
        } catch(IOException e){
            e.printStackTrace();
        }
    }).start();
    return response;
}

我在这行while ((bufferLength = inputStream.read(buffer)) > 0) 中有一个java.lang.ArrayIndexOutOfBoundsException: src.length=2048 srcPos=2048 dst.length=1024 dstPos=0 length=1024

【问题讨论】:

  • getPath()是文件的路径还是图片的URL?
  • 这是网址。这个语句没有问题,因为我可以用静态 URL 来改变它

标签: android save picasso


【解决方案1】:

使用毕加索加载图像很好,有几个优点:

  1. 解压缩图像的内存和磁盘缓存、后处理
  2. 自动创建的单例图像下载器
  3. 一次下载多个

但是你可以尝试使用 Volley,对我来说这是最好的! 关于你的问题,尝试在 logcat 中显示 item.getItem().getPath() 看看路径是否正常,如果你想使用 sdcard 中的图像,路径应该是 sdcard 中的路径

【讨论】:

  • item.getIem().getPath() 没有问题,因为当我将行代码FileOutputStream fileOutput = new FileOutputStream(destination); 注释为fileOutput.close(); 时,图像显示在 ImageView 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 2013-02-02
  • 1970-01-01
相关资源
最近更新 更多