在Android中,以下是实现最简单的方法:
- 从远程服务器加载图像。
- 在ImageView中显示它。
这是我在一个应用程序中真正使用过的方法,我知道它能够有效地工作:
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"
似乎起作用了。如果有人知道,请说明一下,因为文档并没有详细说明。
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
。然后,您只需使用ImageView
的setImageBitmap
方法来显示图像。
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>
*
*/
implementation 'com.example.library:1.0.0'
将 Original Answer 翻译成“最初的回答”。implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.get().load(pictureURL).into(imageView);