package com.basic.security.utils;
|
|
import android.graphics.Bitmap;
|
import android.graphics.BitmapFactory;
|
import android.util.LruCache;
|
import android.widget.ImageView;
|
|
/**
|
* Created by hasee on 2018/7/17.
|
*/
|
|
public class ImageUtils {
|
|
public static LruCache<String, Bitmap> imgCache;
|
|
private static void init() {
|
int maxCache = (int) (Runtime.getRuntime().maxMemory() / 1024);
|
imgCache = new LruCache<String, Bitmap>(maxCache / 8) {
|
@Override
|
protected int sizeOf(String key, Bitmap value) {
|
return value.getByteCount() / 1024;
|
}
|
|
@Override
|
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
|
oldValue.recycle();
|
oldValue = null;
|
super.entryRemoved(evicted, key, oldValue, newValue);
|
}
|
};
|
}
|
|
public static Bitmap setScaleBitmap(String path, ImageView imageView) {
|
if (imgCache == null) {
|
init();
|
}
|
Bitmap bitmap = imgCache.get(path);
|
if (bitmap != null) {
|
imageView.setImageBitmap(bitmap);
|
return bitmap;
|
}
|
BitmapFactory.Options options = new BitmapFactory.Options();
|
options.inJustDecodeBounds = true;
|
BitmapFactory.decodeFile(path, options);
|
int imageWidth = options.outWidth;
|
int imageHeight = options.outHeight;
|
|
int viewWidth = imageView.getWidth();
|
int viewHeight = imageView.getHeight();
|
|
int scale = 1;
|
if (viewWidth == 0 || viewHeight == 0) {
|
imageView.setImageBitmap(BitmapFactory.decodeFile(path));
|
return null;
|
}
|
int scaleWidth = imageWidth / viewWidth;
|
int scaleHeight = imageHeight / viewHeight;
|
if (scaleWidth >= scaleHeight && scaleWidth > 1) {
|
scale = scaleWidth;
|
} else if (scaleWidth < scaleHeight && scaleHeight > 1) {
|
scale = scaleHeight;
|
}
|
options.inSampleSize = scale;
|
options.inJustDecodeBounds = false;
|
options.inPreferredConfig = Bitmap.Config.RGB_565;
|
bitmap = BitmapFactory.decodeFile(path, options);
|
imageView.setImageBitmap(bitmap);
|
imgCache.put(path, bitmap);
|
return bitmap;
|
}
|
}
|