11

在Android中,以下最简单的方法是什么:

  1. 从远程服务器加载图像。
  2. 在 ImageView 中显示它。
4

5 回答 5

21

这是我在应用程序中实际使用的一种方法,我知道它有效:

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"似乎有效。如果有人知道,请说明一下,因为文档并没有真正说明它。

于 2010-06-19T15:05:38.837 回答
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. 然后,您只需要使用setImageBitmapfrom 方法ImageView来显示图像。

于 2010-06-19T13:44:32.323 回答
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://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#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

于 2010-06-29T02:23:35.467 回答
6

你也可以试试这个库: https ://github.com/codingfingers/fastimage

当我们有几个具有相同模式的项目时,lib 出现了 ;) 那么为什么不与他人分享......

于 2012-10-30T16:26:47.373 回答
2

这很简单:

在您的 gradle 脚本中添加此依赖项:

implementation 'com.squareup.picasso:picasso:2.71828'

*2.71828 为当前版本

然后为图像视图执行此操作:

Picasso.get().load(pictureURL).into(imageView);
于 2019-07-03T09:11:21.777 回答