远程图片加载

11
在Android中,以下是实现最简单的方法:
  1. 从远程服务器加载图像。
  2. 在ImageView中显示它。
5个回答

23

这是我在一个应用程序中真正使用过的方法,我知道它能够有效地工作:

try {
    URL thumb_u = new URL("http://www.example.com/image.jpg");
    Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
    myImageView.setImageDrawable(thumb_d);
}
catch (Exception e) {
    // handle it
}

我不知道Drawable.createFromStream的第二个参数是什么,但是传递"src"似乎起作用了。如果有人知道,请说明一下,因为文档并没有详细说明。


对不起,如果这个不起作用,我还没有测试过。我已经编辑了我的答案并添加了另一种方法。 - Felix
1
其他stackoverflow的问题似乎表明“src”是无用的。 - gonzobrains
4
你的代码片段不应该在UI线程中使用,网络操作可能会阻塞应用程序并触发ANR窗口。你必须使用ASynctask或自己的后台线程来管理下载。有一些库,比如https://code.google.com/p/droid4me/wiki/BitmapDownloader可以帮助你正确地管理图像下载。 - Guillaume Perrot

6
到目前为止,最简单的方法是构建一个简单的图像检索器:
public Bitmap getRemoteImage(final URL aURL) {
    try {
        final URLConnection conn = aURL.openConnection();
        conn.connect();
        final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        final Bitmap bm = BitmapFactory.decodeStream(bis);
        bis.close();
        return bm;
    } catch (IOException e) {}
    return null;
}

然后,您只需向该方法提供URL,它就会返回一个Bitmap。然后,您只需使用ImageViewsetImageBitmap方法来显示图像。


你知道如何在 HTTPS 连接中完成这个操作吗? - Woppi

6
请注意这两个答案 - 它们都有可能导致OutOfMemoryException。通过尝试下载大型图像(例如桌面壁纸)来测试应用程序。需要明确的是,有问题的行是:

final Bitmap bm = BitmapFactory.decodeStream(bis);

Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(),"src");

Felix的答案将在catch{}语句中捕获它,您可以在那里做一些处理。

以下是如何解决OutOfMemoryException错误的方法:

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 8;
    Bitmap bmp = null;
    try {
        bmp = BitmapFactory.decodeStream(is, null, options);
    } catch (OutOfMemoryError ome) {
        // TODO - return default image or put this in a loop,
        // and continue increasing the inSampleSize until we don't
        // run out of memory
    }

以下是我在代码中对此的评论

/**
 * Showing a full-resolution preview is a fast-track to an
 * OutOfMemoryException. Therefore, we downsample the preview image. Android
 * docs recommend using a power of 2 to downsample
 * 
 * @see <a
 *      href="https://dev59.com/puo6XIcBkEYKwwoYTzNK#823966">StackOverflow
 *      post discussing OutOfMemoryException</a>
 * @see <a
 *      href="http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize">Android
 *      docs explaining BitmapFactory.Options#inSampleSize</a>
 * 
 */

以下是上述评论中提到的链接: 链接1 链接2


6

4
这很简单: 在你的gradle脚本中添加这个依赖项:

implementation 'com.example.library:1.0.0'

将 Original Answer 翻译成“最初的回答”。
implementation 'com.squareup.picasso:picasso:2.71828'

"最初的回答" 翻译为 "Original Answer"
然后,针对图像视图执行以下操作:
Picasso.get().load(pictureURL).into(imageView);

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