package com.yns.utils;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
/**
* 异步加载网络图片 并且缓存到内存中
*
* @author Administrator
*
*/
public class AsyncImageLoader extends AsyncTask<String, String, Bitmap> {
private ImageView img;
private LruCache<String, Bitmap> lruCache;
private int width;
private int height;
//url 本地ip
private String url;
public AsyncImageLoader(ImageView img, LruCache<String, Bitmap> lruCache,
int width, int height, String url) {
this.img = img;
this.lruCache = lruCache;
this.width = width;
this.height = height;
this.url = url;
}
@Override
protected Bitmap doInBackground(String... arg0) {
// TODO Auto-generated method stub
// 为位图设置100K的缓存
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inTempStorage = new byte[100 * 1024];
// 设置位图颜色显示优化方式
opts.inPreferredConfig = Bitmap.Config.RGB_565;
// 4.设置图片可以被回收,创建Bitmap用于存储Pixel的内存空间在系统内存不足时可以被回收
opts.inPurgeable = true;
// 设置位图缩放比例
opts.inSampleSize = 4;
// 7.解码位图
// decodeStream (InputStream is, Rect outPadding,
// BitmapFactory.Options opts)
Bitmap bitmap = null;
try {
// arg0 是图片名字 如aa.jpg 读者只有一张图片可以 直接写
System.out.println("AsyncImageLoader.doInBackground()"+url + arg0[0]);
bitmap = BitmapFactory.decodeStream(new URL(arg0[0])
.openConnection().getInputStream(), null, opts);
addBitmapToMemoryCache(url + arg0[0], bitmap);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
img.setImageBitmap(result);
}
// 调用LruCache的put 方法将图片加入内存缓存中,要给这个图片一个key 方便下次从缓存中取出来
private void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemoryCache(key) == null) {
lruCache.put(key, bitmap);
}
}
// 调用Lrucache的get 方法从内存缓存中取图片
public Bitmap getBitmapFromMemoryCache(String key) {
return lruCache.get(key);
}
}
android 异步缓冲图片到内存 压缩图片 避免OOM 内存溢出
最新推荐文章于 2021-08-13 16:16:37 发布