如何从Android中的给定网址下载并保存图像?
我正在使用以下方法从url下载单个图像
public static Bitmap getBitmap(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap d = BitmapFactory.decodeStream(is);
is.close();
return d;
} catch (Exception e) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
有时我会得到一个outofmemory异常.
我无法捕捉到内存异常.该应用程序将关闭.怎么预防这个?
是否有更好的下载图像的方法也更快?
我正在尝试从外部存储加载图像.我设置权限,我尝试了不同的方式,但没有一个工作.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(file.toString());
tv.setImageBitmap(bitmap);
Run Code Online (Sandbox Code Playgroud)
还有这个,
FileInputStream streamIn = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(streamIn);
tv.setImageBitmap(bitmap);
streamIn.close();
Run Code Online (Sandbox Code Playgroud)