import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
import android.util.Log;
/**
* <缓存图片工具类>
* @version [版本号, 2014-8-19]
*/
public class BitmapUntils {
private LruCache<String, Bitmap> mMemoryCache;
public BitmapUntils() {
//应用程序最大可用内存,设置图片缓存大小为maxMemory的1/3
int maxMemory = (int) Runtime.getRuntime().maxMemory()/2;
mMemoryCache = new LruCache<String, Bitmap>(maxMemory) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
}
/**
*
* <向内存中加入缓存图片>
* @param filePath [标识缓存]
* @param bitmap [缓存对象类型]
* @return void [返回类型]
*/
public void addBitmap(String filePath, Bitmap bitmap) {
if (getBitmapFromMemCache(filePath) == null && bitmap != null) {
mMemoryCache.put(filePath, bitmap);
Log.i("filePath", "加入缓存");
}
}
/**
* <从内存中获取缓存图片>
* @param filePath [缓存图片的标识]
* @return Bitmap [返回类型]
*/
public Bitmap getBitmapFromMemCache(String filePath) {
return mMemoryCache.get(filePath);
}
/**
* <读取外部设备的图片>
* @param filePath [图片的路径名]
* @return Bitmap [返回类型]
*/
public static Bitmap getBitmapFromFile(String filePath) {
BitmapFactory.Options options=new BitmapFactory.Options();
//options.inSampleSize = 2;//容量变为原来的1/2
FileInputStream is = null;
try {
is = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return BitmapFactory.decodeStream(is,null,options);
}
/**
* <判断当前图片是否存在>
* @param filePath [图片的路径名]
* @return boolean [返回类型;true表示文件存在,反之表示不存在]
*/
public static boolean isFileExists(String filePath) {
try {
File f = new File(filePath);
if (!f.exists()) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
}