在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
. 然后,您只需要使用setImageBitmap
from 方法ImageView
来显示图像。
小心这里的两个答案 - 他们都有机会出现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>
*
*/
你也可以试试这个库: https ://github.com/codingfingers/fastimage
当我们有几个具有相同模式的项目时,lib 出现了 ;) 那么为什么不与他人分享......
这很简单:
在您的 gradle 脚本中添加此依赖项:
implementation 'com.squareup.picasso:picasso:2.71828'
*2.71828 为当前版本
然后为图像视图执行此操作:
Picasso.get().load(pictureURL).into(imageView);