图片的异步加载和缓存

package com.mymusicplayer.util;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;


public class MyImageLoader {
static LruCache<String, Bitmap> lruCache=null;
static{
int maxSize=4*1024*1024;
lruCache=new LruCache<String, Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight();
}
};
}
/**
* @param imageView 设置图片的控件
* @param context 上下文
* @param url 图片资源路径
*
*/
public static void setBitmapFromLruCache(ImageView imageView,Context context,String path){
if (TextUtils.isEmpty(path)) {
return; 
}
Bitmap bitmap=null;
//先从内存缓存中找缓存的图片
bitmap=getBitmapFromMemoryCache(path);
if (bitmap!=null) {
Log.i("TAG", "MemoryCache.bitmap="+bitmap.toString());
imageView.setImageBitmap(bitmap);
return;
}
//再从应用的缓存目录中查找
bitmap=getBitmapFromFileCache(context,path);
if (bitmap!=null) {
Log.i("TAG", "FileCache.bitmap="+bitmap.toString());
imageView.setImageBitmap(bitmap);
return;
}
//再从网络上去异步获取
getBitmapAsyncLoad(context,imageView,path);
}


//从内存缓存中找缓存的图片
private static Bitmap getBitmapFromMemoryCache(String path){
Bitmap bitmap=null;
if (path!=null) {
bitmap=lruCache.get(path);
}
return bitmap;
}
//从应用的缓存目录中获取数据
private static Bitmap getBitmapFromFileCache(Context context,String path){
String filename=path.substring(path.lastIndexOf("/")+1);
Bitmap bitmap=null;
//获得应用的缓存目录
File cacheDir=context.getCacheDir();
if (cacheDir!=null) {
File[] files=cacheDir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].getName().equals(filename)) {
bitmap=BitmapFactory.decodeFile(files[i].getAbsolutePath());
}
}
}
return bitmap;
}
//从网络上去异步获取图片数据
private static void getBitmapAsyncLoad(Context context,
ImageView imageView, String path) {
MyAsyncTask task=new MyAsyncTask(context, imageView);
task.execute(path);
}
static class MyAsyncTask extends AsyncTask<String, Void, Bitmap>{
private Context context;
private ImageView imageView_header;

public MyAsyncTask(Context context, ImageView imageView_header) {
super();
this.context = context;
this.imageView_header = imageView_header;
}

@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap=null;
String path=params[0];
try {
URL url=new URL(path);

HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.setDoInput(true);


if (connection.getResponseCode()==200) {
InputStream inputStream=connection.getInputStream();
//把返回的图片资源按比例缩放进行压缩
byte[] datas=StreamUtil.getDatasFromStream(inputStream);
bitmap=compressBitmap(datas);
//存入内存缓存、应用缓存
if (bitmap!=null) {
//放到内存缓存中
lruCache.put(path, bitmap);
//放到应用缓存中
bitmapCacheFile(context,path,bitmap);
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException 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) {
Log.i("TAG", "Intenet.bitmap="+result.toString());
imageView_header.setImageBitmap(result);
super.onPostExecute(result);
}


//将图片缓存到应用内存中
private void bitmapCacheFile(Context context2, String path,
Bitmap bitmap) {
File cacheFile=context2.getCacheDir();
if (!cacheFile.exists()) {
cacheFile.mkdir();
}
String fileName=path.substring(path.lastIndexOf("/")+1);
File file=new File(cacheFile, fileName);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//将图片读入文件中
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
}


//把返回的图片资源按比例缩放进行压缩
private Bitmap compressBitmap(byte[] imageDatas) {
BitmapFactory.Options options=new BitmapFactory.Options();
//对二进制数据解码时仅做图片的边界处理
options.inJustDecodeBounds=true;


BitmapFactory.decodeByteArray(imageDatas,0,imageDatas.length, options);
//获取图片的实际的宽度,高度
final int outWidth=options.outWidth;
final int outHight=options.outHeight;


int targetWidth=70;
int targetHight=70;

//计算压缩比例
int wbl=Math.round((float)outWidth/(float)targetWidth);
int hbl=Math.round((float)outHight/(float)targetHight);

int bl=wbl>hbl?wbl:hbl;

if (bl<0) {
bl=1;
}
options.inSampleSize=bl;
options.inJustDecodeBounds=false;


Bitmap bitmap=BitmapFactory.decodeByteArray(imageDatas, 0, imageDatas.length,options);


return bitmap;
}


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值