【发布时间】:2017-03-12 16:26:39
【问题描述】:
如何从 URL 加载图像并将其保存在 android 设备的内存中?不要说我使用毕加索或 oser 图书馆。 我需要: 如果设备获得互联网连接,我将图像从 url 加载到 ImageView 并将其保存在设备的内存中,否则我需要将保存图像之一加载到 imageView。感谢帮助
附:对不起,我可能会在问题中犯一些错误,因为我不太懂英语。 这是我的课:
public class ImageManager {
String file_path;
Bitmap bitmap = null;
public Bitmap donwoaledImageFromSD() {
File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
private void savebitmap() {
File file = new File("first");
file_path = file.getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchImage(final String url, final ImageView iView) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
try {
InputStream in = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
savebitmap();
} catch (Exception e) {
donwoaledImageFromSD();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(url);
}
}
【问题讨论】:
-
你不要使用可靠的库,如 Glide、Picaso 等
-
这是不使用标准图书馆(Glide、Picaso 等)的标准之一
-
请提供minimal reproducible example 说明您尝试过的方法以及遇到的具体问题。
标签: android file url bitmap fileoutputstream