<pre name="code" class="java">
/**
* 下载服务器网络图片
* */
public class DownBitmap {
private DownBitmap() {
}
private static DownBitmap my = null;
public static synchronized DownBitmap getInstance() {
if (my == null)
my = new DownBitmap();
return my;
}
// 获取网络图片下载时返回的流
public InputStream getInputStream(String Biturl) {
// 使用get请求方式获取图片资源
HttpGet get = new HttpGet(Biturl);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000);
HttpConnectionParams.setSoTimeout(httpParams, 30 * 1000);
HttpClient httpClient = new DefaultHttpClient(httpParams);
try {
HttpResponse hr = httpClient.execute(get);
if (hr.getStatusLine().getStatusCode() == 200) {
return hr.getEntity().getContent();// 得到服务器返回的输入流
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 建立response连接从而方便获取状态吗
return null;
}
}
/**
* 把网络图片保存到本地
* 1.强引用,正常实例化一个对象。 jvm无论内存是否够用系统都不会释放这块内存
* 2.软引用(softReference):当我们系统内存不够时,会释放掉
* 3.弱引用:当我们系统清理内存时发现是一个弱引用对象,直接清理掉
* 4.虚引用:当我们清理内存时会 把虚引用对象放入一个清理队列当中, 让我们程序员保存当前对象的状态
*
* FileUtiles 作用: 用来向我们的sdcard保存网络接收来的图片 </BR> </BR> By:苦涩 </BR> 联系作者:QQ
* 534429149
* */
public class FileUtiles {
private Context ctx;
public FileUtiles(Context ctx) {
this.ctx = ctx;
}
// 获取手机在sdcard保存图片的地址
public String getAbsolutePath() {
File root = ctx.getExternalFilesDir(null);
// 返回手机端的绝对路径,当我们软件卸载,以及清理缓存时会被清理掉
if (root != null)
return root.getAbsolutePath();
return null;
}
// 判断图片在本地缓存当中是否存在,如果存在返回一个true
public boolean isBitmap(String name) {
File root = ctx.getExternalFilesDir(null);
// file地址拼接
File file = new File(root, name);
return file.exists();
}
// 添加到本地缓存当中
public void saveBitmap(String name, Bitmap bitmap) {
if (bitmap == null)
return;
// 如果sdcard不能使用
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_UNMOUNTED)) {
return;
}
// 拼接图片要保存到sd卡的地址
String BitPath = getAbsolutePath() + "/" + name;
// mtn/sdcard/android/com.a njoyo.zhangxinyi/files/
try {
FileOutputStream fos = new FileOutputStream(BitPath);
/**
* bitmap.compress把图片通过输出流保存到本地 Bitmap.CompressFormat.JPEG 保存图片的格式
* 100 保存到本地的图片质量,需要压缩时适当调整大小
*
* */
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 控制图片的加载类
*
* 列表在滑动过程时,没有图片会进行下载,并保存到sdcard与
* imageCaches 当中去,使用软引用进行封装,如果内存不够时
* 我们的imageCaches 当中的Bitmap对象会被清理掉,图片被释放掉
* 再次需要加载的时候,先从1级缓存当中获取,如果没有的话,去
* 本地获取,本地也获取不到的话,去网络下载。
* 一级缓存作用:对于listview当中刚刚滑动过的item显示的图片进行保存
* 二级缓存作用:对于listview当中很久前查看的图片或已经被释放掉图片
* 进行保存
* </BR> </BR> By:苦涩 </BR> 联系作者:QQ 534429149
* */
public class LoadImg {
//下载图片最大并行线程数
private static final int Max = 5;
//图片的一级缓存,保存在我们程序内部
private Map<String,SoftReference<Bitmap>> imageCaches = null;
//查看本地缓存工具类
private FileUtiles fileUtiles;
//android 提供给我们的一个线程池,使用方便
private ExecutorService threadPools = null;
//初始化上面的相关的变量
public LoadImg(Context ctx){
imageCaches = new HashMap<String, SoftReference<Bitmap>>();
fileUtiles = new FileUtiles(ctx);
}
//加载图片时,入口
public Bitmap loadImage(final ImageView imageView,
final String imageUrl,
final ImageDownloadCallBack imageDownloadCallBack){
//imageUrl 由于其唯一型,把他作为我们map当中的key
//图片名称
final String filename = imageUrl.substring(imageUrl.lastIndexOf("/")+1,
imageUrl.length());
//图片保存到本地时的地址
String filepath = fileUtiles.getAbsolutePath()+"/"+filename;
//查找一级缓存,看看是否有这张图片
//如果map当中有这个key返回一个true
if(imageCaches.containsKey(imageUrl)){
//找到对应图片软引用的封装
SoftReference<Bitmap> soft = imageCaches.get(imageUrl);
//从软引用当中获取图片
Bitmap bit = soft.get();
if(bit != null)
return bit;
//从我们的一级缓存(程序内部获取图片)
}
//从二级缓存当中获取图片
if(fileUtiles.isBitmap(filename)){
Bitmap bit = BitmapFactory.decodeFile(filepath);
//在二级缓存读取的时候直接添加到一级缓存当中
imageCaches.put(imageUrl, new SoftReference<Bitmap>(bit));
return bit;
}
//一级缓存,二级缓存都不存在,直接到网络加载
if(imageUrl != null && !imageUrl.equals("")){
if(threadPools == null){
//实例化我们的线程池
threadPools = Executors.newFixedThreadPool(Max);
}
//下载回图片回调Handler
final Handler hand = new Handler(){
@Override
public void handleMessage(Message msg) {
//如果图片下载成功,并且回调对象不为空时
if(msg.what == 111 &&
imageDownloadCallBack != null){
Bitmap bit = (Bitmap) msg.obj;
//调用回调自定义适配器的接口方法传递数据
imageDownloadCallBack.onImageDownload(imageView, bit);
}
super.handleMessage(msg);
}
};
//下载图片线程
Thread thread = new Thread(){
public void run(){
//网络下载时的字节流
InputStream inputStream = DownBitmap.
getInstance().
getInputStream(imageUrl);
//图片压缩为原来的一半
BitmapFactory.Options op = new BitmapFactory.Options();
op.inSampleSize = 2;
Bitmap bit = BitmapFactory.decodeStream(inputStream, null, op);
if(bit != null){
//添加到一级缓存当中
imageCaches.put(imageUrl,new SoftReference<Bitmap>(bit));
//添加到二级缓存
fileUtiles.saveBitmap(filename, bit);
//传递给Handler
Message msg = hand.obtainMessage();
msg.what = 111;
msg.obj = bit;
hand.sendMessage(msg);
}
}
};
threadPools.execute(thread);
}
return null;
}
//通过回调机制设置图片时的接口(类似于Button的Onclick)
public interface ImageDownloadCallBack{
//ImageView 你所想要设定的imageview Bitmap 想要设定的图片
void onImageDownload(ImageView imageView,Bitmap bitmap);
}
}
应用实例:
// 添加图片方法
private void addImg() {
mShop_details_photo.setTag(Model.SHOPLISTIMGURL + info.getIname());
Bitmap bit = loadImg.loadImage(mShop_details_photo,
Model.SHOPLISTIMGURL + info.getIname(),
new ImageDownloadCallBack() {
public void onImageDownload(ImageView imageView,
Bitmap bitmap) {
// 不需要按照tag查找图片,不存在img复用问题
mShop_details_photo.setImageBitmap(bitmap);
}
});
if (bit != null) {
mShop_details_photo.setImageBitmap(bit);
}
}