Android下载网络图片

下载网络图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 第一步:根据流得到bitmap
// 方案1
Bitmap bitmap = Glide.with(applicationContext)
.load(url)
.asBitmap()
.into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
// 方案2
Bitmap bitmap = BitmapFactory.decodeStream(new URL(url).openStream());

// 压缩图片
// bitmap = Bitmap.createScaledBitmap(bitmap, 120, 120, true);

// 第二步:保存成文件
// 保存图片
File imgDir = new File(getDiskCacheDir(applicationContext), "image_caches");
if (!imgDir.exists()) {
imgDir.mkdirs();
}
File imgFile = new File(imgDir, fileName);
fileOutputStream = new FileOutputStream(imgFile);
Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.PNG;
bitmap.compress(compressFormat, 100, fileOutputStream);
fileOutputStream.flush();

Glide预加载图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void preloadImage(Context context, AdZone adZone) {
for (AdZone.Item item : adZone.getItems()) {
new Thread(() -> {
try {
Glide.with(context.getApplicationContext())
.load(item.getPic())
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}).start();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Glide.with(getApplicationContext())
.load(pic)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(new GlideDrawableImageViewTarget(ivWelcome) {
@Override
protected void setResource(GlideDrawable resource) {
// https://github.com/bumptech/glide/issues/275
super.setResource(resource);

ivWelcome.setOnClickListener(v -> {
sendAdZoneItemBroadcast(item);
});
ivWelcome.setVisibility(View.VISIBLE);

// set countDown
toCountDown();
}

@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
}
});

主要介绍Android图片OutOfMemory异常bitmap size exceeds VM budget的原因及解决方法,顺带提及Dalvik heap size