您的位置:首页 > 其它

加载远程图片,可设置保存到内存卡

2015-02-04 13:36 309 查看
使用方法:

<span style="color:#333333;">ImageView imgview = (ImageView) findViewById(R.id.imageView1);
AsynImageLoader asynImageLoader = new AsynImageLoader("/bala/cache/images/");</span>
<span style="color:#333333;">asynImageLoader.showImageAsyn(imgview, "http://www.balayl.com/uploadfile/2015/0116/20150116012942876.jpg", R.drawable.a115271766,true);</span>


</pre><pre name="code" class="java">
AsynImageLoader类
package com.zm.bala.utils;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.R.bool;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

public class AsynImageLoader {
private static final String TAG = "AsynImageLoader";
// 缓存下载过的图片的Map
private Map<String, SoftReference<Bitmap>> caches;
// 任务队列
private List<Task> taskQueue;
private boolean isRunning = false;
private String CachePath ;//本地缓存图片的目录
public boolean down;
public AsynImageLoader(String cachePath){
// 初始化变量
CachePath = cachePath;
caches = new HashMap<String, SoftReference<Bitmap>>();
taskQueue = new ArrayList<AsynImageLoader.Task>();
// 启动图片下载线程
isRunning = true;
new Thread(runnable).start();
}

/**
*
* @param imageView 需要延迟加载图片的对象
* @param url 图片的URL地址
* @param resId 图片加载过程中显示的图片资源
* @param down0 设置为true,即使缓存中有该图片,也去网络下载,设置为false,如果本地存在,则显示本地图片,如果本地不存在,去下载然后显示
*/
public void showImageAsyn(ImageView imageView, String url, int resId,boolean down0){
down = down0;
imageView.setTag(url);
Bitmap bitmap = loadImageAsyn(url, getImageCallback(imageView, resId));

if(bitmap == null){
imageView.setImageResource(resId);
}else{
imageView.setImageBitmap(bitmap);
}
}

public Bitmap loadImageAsyn(String path, ImageCallback callback){
// 判断缓存中是否已经存在该图片
if(caches.containsKey(path)){
// 取出软引用
SoftReference<Bitmap> rf = caches.get(path);
// 通过软引用,获取图片
Bitmap bitmap = rf.get();
// 如果该图片已经被释放,则将该path对应的键从Map中移除掉
if(bitmap == null){
caches.remove(path);
}else{
// 如果图片未被释放,直接返回该图片
return bitmap;
}
}else{
// 如果缓存中不常在该图片,则创建图片下载任务
Task task = new Task();
task.path = path;
task.callback = callback;
if(!taskQueue.contains(task)){
taskQueue.add(task);
// 唤醒任务下载队列
synchronized (runnable) {
runnable.notify();
}
}
}

// 缓存中没有图片则返回null
return null;
}

/**
*
* @param imageView
* @param resId 图片加载完成前显示的图片资源ID
* @return
*/
private ImageCallback getImageCallback(final ImageView imageView, final int resId){
return new ImageCallback() {

@Override
public void loadImage(String path, Bitmap bitmap) {
if(path.equals(imageView.getTag().toString())){
imageView.setImageBitmap(bitmap);
}else{
imageView.setImageResource(resId);
}
}
};
}

private Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
// 子线程中返回的下载完成的任务
Task task = (Task)msg.obj;
// 调用callback对象的loadImage方法,并将图片路径和图片回传给adapter
task.callback.loadImage(task.path, task.bitmap);
}

};

private Runnable runnable = new Runnable() {

@Override
public void run() {
while(isRunning){
// 当队列中还有未处理的任务时,执行下载任务
while(taskQueue.size() > 0){
// 获取第一个任务,并将之从任务队列中删除
Task task = taskQueue.remove(0);
// 将下载的图片添加到缓存
task.bitmap = PicUtil.getbitmapAndwrite(task.path,CachePath,down);
caches.put(task.path, new SoftReference<Bitmap>(task.bitmap));
if(handler != null){
// 创建消息对象,并将完成的任务添加到消息对象中
Message msg = handler.obtainMessage();
msg.obj = task;
// 发送消息回主线程
handler.sendMessage(msg);
}
}

//如果队列为空,则令线程等待
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};

//回调接口
public interface ImageCallback{
void loadImage(String path, Bitmap bitmap);
}

class Task{
// 下载任务的下载路径
String path;
// 下载的图片
Bitmap bitmap;
// 回调对象
ImageCallback callback;

@Override
public boolean equals(Object o) {
Task task = (Task)o;
return task.path.equals(path);
}
}
}
PicUtil 类

package com.zm.bala.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class PicUtil {
/**
* 根据一个网络连接(String)获取bitmap图像 此方法 不缓存到本地文件
* @param imageUri
* @return
* @throws MalformedURLException
*/
public static Bitmap getbitmap(String imageUri) {
// 显示网络上的图片
Bitmap bitmap = null;
try {
URL myFileUrl = new URL(imageUri);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return bitmap;
}

/**
* 加载网络图片,如果本地缓存中存在该图片,返回本地的图片,如果没有,先去下载到本地,然后返回
* @param context
* @param imageUri
* @return
* @throws MalformedURLException
*/
public static Bitmap getbitmapAndwrite(String imageUri,String cachepath,boolean down) {
Bitmap bitmap = null;
try {

File cacheFile = FileUtil.getCacheFile(imageUri,cachepath);
//如果本地不存在缓存的图片,或者设置必须下载,去网络上下载
if (cacheFile.exists()==false || down) {
// 显示网络上的图片
URL myFileUrl = new URL(imageUri);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();

InputStream is = conn.getInputStream();
BufferedOutputStream bos = null;
bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
byte[] buf = new byte[1024];
int len = 0;
// 将网络上的图片存储到本地
while ((len = is.read(buf)) > 0) {
bos.write(buf, 0, len);
}

is.close();
bos.close();
}

// 从本地加载图片
bitmap = BitmapFactory.decodeFile(cacheFile.getCanonicalPath());

} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}


FileUtil类

package com.zm.bala.utils;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

public class FileUtil {

public static File getCacheFile(String imageUri,String cachepath){

File cacheFile = null;
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File sdCardDir = Environment.getExternalStorageDirectory();
String fileName = getFileName(imageUri);

File dir = new File(sdCardDir.getCanonicalPath() + cachepath);
if (!dir.exists()) {
dir.mkdirs();
}
cacheFile = new File(dir, fileName);
}
} catch (IOException e) {
e.printStackTrace();
}

return cacheFile;
}
/**
* 获取文件名,如果是.jpg等正常格式图片,返回原图片名, 如果是动态图片地址,返回.png的md5处理的文件名
* @param path
* @return
*/
public static String getFileName(String path) {
int index = path.lastIndexOf("/");
String lastone = path.substring(index + 1);
String returns="";
if (lastone.contains(".jpg") || lastone.contains(".jpeg") || lastone.contains(".gif") || lastone.contains(".png")) {
returns = lastone;
}else{
returns = MD5Util.MD5(path)+".png";
}
return returns;
}

}


清理缓存的图片类:

package com.zm.bala.utils;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import android.os.Environment;
import android.os.StatFs;
public class RemoveCacheFile {
private int MB=1024;
private int CACHE_SIZE=10;//5M缓存
private int FREE_SD_SPACE_NEEDED_TO_CACHE=1;//最小空闲空间M
/**
*计算存储目录下的文件大小,当文件总大小大于规定的CACHE_SIZE或者sdcard剩余空间小于FREE_SD_SPACE_NEEDED_TO_CACHE的规定
* 那么删除40%最近没有被使用的文件
* @param dirPath
* @param filename
*/
private void removeCache(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null) {
return;
}
int dirSize = 0;
for (int i = 0; i < files.length;i++) {
//if(files[i].getName().contains(WHOLESALE_CONV)) {
dirSize += files[i].length();
//}
}
if (dirSize > CACHE_SIZE * MB ||FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
int removeFactor = (int) ((0.4 *files.length) + 1);

Arrays.sort(files, new FileLastModifSort());

for (int i = 0; i <removeFactor; i++) {

// if(files[i].getName().contains(WHOLESALE_CONV)) {

files[i].delete();

//    }

}

}

}

/**
* 计算sdcard上的剩余空间
* @return
*/
private int freeSpaceOnSd() {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory() .getPath());
double sdFreeMB = ((double)stat.getAvailableBlocks() * (double) stat.getBlockSize()) / MB;
return (int) sdFreeMB;
}
/**
* 修改文件的最后修改时间
* @param dir
* @param fileName
*/
private void updateFileTime(String dir,String fileName) {
File file = new File(dir,fileName);
long newModifiedTime =System.currentTimeMillis();
file.setLastModified(newModifiedTime);
}
/**
* TODO 根据文件的最后修改时间进行排序 *
*/
class FileLastModifSort implements Comparator<File>{
public int compare(File arg0, File arg1) {
if (arg0.lastModified() >arg1.lastModified()) {
return 1;
} else if (arg0.lastModified() ==arg1.lastModified()) {
return 0;
} else {
return -1;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: