package com.snda.lottery.common;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.snda.lottery.app.api.ApiClient;
import com.snda.lottery.util.FileUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
/**
* 异步线程加载图片工具类
* 使用说明:
* BitmapManager bmpManager;
* bmpManager = new BitmapManager(BitmapFactory.decodeResource(context.getResources(), R.drawable.loading));
* bmpManager.loadBitmap(imageURL, imageView);
* @author wulianghuan
* @version 1.0
* @created 2014-06-08
*/
public class BitmapManager {
private static HashMap<String, SoftReference<Bitmap>> cache;
private static ExecutorService pool;
private static Map<ImageView, String> imageViews;
private Bitmap defaultBmp;
// SD卡上图片储存地址
private final static String SAVE_PATH = Environment.getExternalStorageDirectory().getPath() + "/snda_lottery/";
static {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5); //固定线程池
imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
}
public BitmapManager(){}
public BitmapManager(Bitmap def) {
this.defaultBmp = def;
}
/**
* 设置默认图片
* @param bmp
*/
public void setDefaultBmp(Bitmap bmp) {
defaultBmp = bmp;
}
/**
* 加载图片
* @param url
* @param imageView
*/
public void loadBitmap(String url, ImageView imageView) {
loadBitmap(url, imageView, this.defaultBmp, 0, 0);
}
/**
* 加载图片-可设置加载失败后显示的默认图片
* @param url
* @param imageView
* @param defaultBmp
*/
public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp) {
loadBitmap(url, imageView, defaultBmp, 0, 0);
}
/**
* 加载图片-可指定显示图片的高宽
* @param url
* @param imageView
* @param width
* @param height
*/
public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp, int width, int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap != null) {
//显示缓存图片
imageView.setImageBitmap(bitmap);
} else {
//加载SD卡中的图片缓存
String filename = FileUtils.getFileName(url);
String filepath = imageView.getContext().getFilesDir() + File.separator + filename;
File file = new File(filepath);
if(file.exists()){
//显示SD卡中的图片缓存
Bitmap bmp = getBitmap(imageView.getContext(), filename);
imageView.setImageBitmap(bmp);
}else{
//线程加载网络图片
imageView.setImageBitmap(defaultBmp);
queueJob(url, imageView, width, height);
}
}
}
/**
* 从缓存中获取图片
* @param url
*/
public Bitmap getBitmapFromCache(String url) {
Bitmap bitmap = null;
if (cache.containsKey(url)) {
bitmap = cache.get(url).get();
}
return bitmap;
}
/**
* 从网络中加载图片
* @param url
* @param imageView
* @param width
* @param height
*/
public void queueJob(final String url, final ImageView imageView, final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
try {
//向SD卡中写入图片缓存
saveImage(FileUtils.getFileName(url), (Bitmap) msg.obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
pool.execute(new Runnable() {
public void run() {
Message message = Message.obtain();
message.obj = downloadBitmap(url, width, height);
handler.sendMessage(message);
}
});
}
/**
* 下载图片-可指定显示图片的高宽
* @param url
* @param width
* @param height
*/
private Bitmap downloadBitmap(String url, int width, int height) {
Bitmap bitmap = null;
try {
//http加载图片
bitmap = ApiClient.getNetBitmap(url);
if(width > 0 && height > 0) {
//指定显示图片的高宽
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
}
//放入缓存
cache.put(url, new SoftReference<Bitmap>(bitmap));
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 获取bitmap
* @param context
* @param fileName
* @return
*/
public static Bitmap getBitmap(Context context,String fileName) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = context.openFileInput(fileName);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}finally{
try {
fis.close();
} catch (Exception e) {}
}
return bitmap;
}
//
private void saveBitmap() {
//
FileOutputStream outStream = new FileOutputStream(localFile);
//
InputStream inputStream = conn.getInputStream();
//
byte[] buffer = new byte[1024];
//
int len = 0;
//
while( (len = inputStream.read(buffer)) != -1){
//
outStream.write(buffer, 0, len);
//
}
//
inputStream.close();
//
outStream.close();
//
}
/**
* 写图片文件
* 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下
* @throws IOException
*/
public static void saveImage(String fileName, Bitmap bitmap) throws IOException
{
saveImage(fileName, bitmap, 100);
}
public static void saveImage(String fileName, Bitmap bitmap, int quality) throws IOException
{
if(bitmap==null || fileName==null)
return;
// 保存的文件路径
File file = new File(SAVE_PATH+fileName);
FileOutputStream fos = new FileOutputStream(file);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, stream);
byte[] bytes = stream.toByteArray();
fos.write(bytes);
fos.close();
}
}