标签:
public class ImageResizer {
private static final String TAG = "ImageResizer";
public ImageResizer() {
}
public Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
//1、 将BitmapFactory.Options的inJustDecodeBounds设置为true并加载图片
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 2、从BitmapFactory.Options取出图片的原始宽高信息
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// 4、设置injustDecodBounds为false然后重新加载图片
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
if (reqWidth == 0 || reqHeight == 0) {
return 1;
}
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
Log.d(TAG, "origin, w= " + width + " h=" + height);
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
//3、结合采样率规则并结合View的所需大小计算采样率inSampleSize
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
Log.d(TAG, "sampleSize:" + inSampleSize);
return inSampleSize;
}
}
int maxMemory = (int)(Runtime.getRuntime().maxMemory()/1024);
int cacheSize = maxMemory/8;
mMemory = new LruCache<String,Bitmap>(cacheSize){
@override
protected int sizeOf(String key,Bitmap bitmap){
return bitmap.getRowBytes().bitmap.getHeight()/1024;
}
}
private static final long DISK_CACHE_SIZE = 1024*1024*50;//50MB
File diskCacheDir = getDiskCacheDir(mContext,"bitmap");
if(!diskCacheDir.exits()){
diskCacheDir.mkdirs();
}
mDiskLruCache = DisLruCache.open(diskCacheDir,1,1,DISK_CACHE_SIZE);//存储路径,可以放在SD卡的存储目录,也可以选择SD卡的其他目录
//版本号,一般为1
//单个节点对应数据的个数,一般1
//缓存的总大小
//将url转换成key
private String hashKeyFormUrl(String url){
String cacheKey;
try{
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(url.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
}catch(NoSuchAlgorithmException e){
cacheKey = String.valueOf(url.hashCode());
}
return cacheKey;
}
private String bytesToHexString(byte[] bytes){
StringBuilder sb = new StringBuilder();
for(int i = 0;i<byte.length;i++){
String hex = Integer.toHexString(0xFF & bytes[i]);
if(hex.length()==1){
sb.append(‘0‘);
}
sb.append(hex);
}
return sb.toString();
}
String key = hashKeyFormUrl(url);
DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if(edit !=null){
OutputStream outputStream = editor.newOutputStream(DISK_CACHE_INDEX)
}
标签:
原文地址:http://www.cnblogs.com/fruitbolgs/p/5232414.html