不解释大家懂得,在listview 或grid或viewpager等大量大尺寸图片时,会造成OOM
这里是优化图片内存的一个方法,注释写的很 明确..
public Bitmap getBitmapFromNet(final String url,final int width,final int height){//从网络下载图片
try {
//图片内存算法
//width*height*Config(480*320*ARGB_8888)——>480*320*4 byte
BitmapFactory.Options opt = new BitmapFactory.Options();
/*组合使用*/
opt.inPurgeable = true;
opt.inInputShareable = true;
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.outWidth = width;
opt.outHeight = height;
opt.inJustDecodeBounds = true;//设置为true将不会返回真正大小
int yRatio = (int)Math.ceil(opt.outHeight/height);
int xRatio = (int)Math.ceil(opt.outWidth/width);
if (yRatio > 1 || xRatio > 1){
if (yRatio > xRatio) {
opt.inSampleSize = yRatio; //缩放值
}
else {
opt.inSampleSize = xRatio;
}
}
Bitmap bitmap = BitmapFactory.decodeStream(new URL(url).openStream(),null,opt);
//bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
cache.put(url, new SoftReference<Bitmap>(bitmap));//保存缓存--------->缓存Map
return bitmap;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
本文链接