Android开发之超强图片工具类开发之超强图片工具类BitmapUtil完整实例完整实例
主要介绍了Android开发之超强图片工具类BitmapUtil,结合完整实例形式分析了Android图片的常用操作技巧,包括图片的加载、转换、缩放、计算等相关操作技巧,需要
的朋友可以参考下
本文实例讲述了Android开发之超强图片工具类BitmapUtil。分享给大家供大家参考,具体如下:
说明:为了方便大家使用,本人把大家常用的图片处理代码集中到这个类里
使用了LruCache与SoftReference
/**
* 图片加载及转化工具 ----------------------------------------------------------------------- 延伸:一个Bitmap到底占用多大内存?系统给每个应用程序分配多大内存? Bitmap占用的内存为:像素总数
* * 每个像素占用的内存。在Android中, Bitmap有四种像素类型:ARGB_8888、ARGB_4444、ARGB_565、ALPHA_8, 他们每个像素占用的字节数分别为4、2、2、1。因此,一个2000*1000的ARGB_8888
* 类型的Bitmap占用的内存为2000*1000*4=8000000B=8MB。
*
* @author chen.lin
*
*/
public class BitmapUtil {
/**
* 1)软引用 ,已经不适合缓存图片信息,加载图片时会出现重叠的现象
* 2)Android 3.0 (API Level 11)中,图片的数据会存储在本地的内存当中
* 因而无法用一种可预见的方式将其释放,这就有潜在的风险造成应用程序的内存溢出并崩溃,
* 3)因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,
这让软引用和弱引用变得不再可靠。
*
*/
private static Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
/**
* 初始化lrucache,最少使用最先移除,LruCache来缓存图片,
* 当存储Image的大小大于LruCache设定的值,系统自动释放内存,
*/
private static LruCache<String, Bitmap> mMemoryCache;
static {
final int memory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = memory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
protected int sizeOf(String key, Bitmap value) {
// return value.getByteCount() / 1024;
return value.getHeight() * value.getRowBytes();
}
};
}
// ---lrucache----------------------------------------------------
/**
* 添加图片到lrucache
*
* @param key
* @param bitmap
*/
public synchronized void addBitmapToMemCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
if (key != null & bitmap != null) {
mMemoryCache.put(key, bitmap);
}
}
}
/**
* 清除缓存
*/
public void clearMemCache() {
if (mMemoryCache != null) {
if (mMemoryCache.size() > 0) {
mMemoryCache.evictAll();
}
mMemoryCache = null;
}
}
/**
* 移除缓存
*/
public synchronized void removeMemCache(String key) {
if (key != null) {
if (mMemoryCache != null) {
Bitmap bm = mMemoryCache.remove(key);
if (bm != null)
bm.recycle();
}
}
}
/**
* 从lrucache里读取图片
*
* @param key
* @return
*/
public Bitmap getBitmapFromMemCache(String key) {
if (key != null) {
return mMemoryCache.get(key);
}
return null;
}
/**
* 加载图片
*
* @param context
* @param resId
* @param imageView
*/
public void loadBitmap(Context context, int resId, ImageView imageView) {
final String imageKey = String.valueOf(resId);
final Bitmap bitmap = getBitmapFromMemCache(imageKey);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageResource(resId);
BitmapWorkerTask task = new BitmapWorkerTask(context);
task.execute(resId);
}
}
/**
* 任务类
*
* @Project App_View
* @Package com.android.view.tool
* @author chenlin