本文实例讲述了Android开发之超强图片工具类BitmapUtil。分享给大家供大家参考,具体如下:
说明:为了方便大家使用,本人把大家常用的图片处理代码集中到这个类里
使用了LruCache与SoftReference
public class BitmapUtil {
private static Map> imageCache = new HashMap>();
private static LruCache mMemoryCache;
static {
final int memory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = memory / 8;
mMemoryCache = new LruCache(cacheSize) {
protected int sizeOf(String key, Bitmap value) {
// return value.getByteCount() / 1024;
return value.getHeight() * value.getRowBytes();
}
};
}
// ---lrucache----------------------------------------------------
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();
}
}
}
public Bitmap getBitmapFromMemCache(String key) {
if (key != null) {
return mMemoryCache.get(key);
}
return null;
}
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);
}
}
class BitmapWorkerTask extends AsyncTask {
private Context mContext;
public BitmapWorkerTask(Context context) {
mContext = context;
}
// 在后台加载图片。
@Override
protected Bitmap doInBackground(Integer... params) {
final Bitmap bitmap = decodeSampledBitmapFromResource(mContext.getResources(), params[0], 100, 100);
addBitmapToMemCache(String.valueOf(params[0]), bitmap);
return bitmap;
}
}
// --软引用---------------------------------------------------------
public static void addBitmapToCache(String path) {
// 强引用的Bitmap对象
Bitmap bitmap = BitmapFactory.decodeFile(path);
// 软引用的Bitmap对象
SoftReference softBitmap = new SoftReference(bitmap);
// 添加该对象到Map中使其缓存
imageCache.put(path, softBitmap);
}
public static Bitmap getBitmapByPath(String path) {
// 从缓存中取软引用的Bitmap对象
SoftReference softBitmap = imageCache.get(path);
// 判断是否存在软引用
if (softBitmap == null) {
return null;
}
// 取出Bitmap对象,如果由于内存不足Bitmap被回收,将取得空
Bitmap bitmap = softBitmap.get();
return bitmap;
}
public Bitmap loadBitmap(final String imageUrl, final ImageCallBack imageCallBack) {
SoftReference reference = imageCache.get(imageUrl);
if (reference != null) {
if (reference.get() != null) {
return reference.get();
}
}
final Handler handler = new Handler() {
public void handleMessage(final android.os.Message msg) {
// 加入到缓存中
Bitmap bitmap = (Bitmap) msg.obj;
imageCache.put(imageUrl, new SoftReference(bitmap));
if (imageCallBack != null) {
imageCallBack.getBitmap(bitmap);
}
}
};
new Thread() {
public void run() {
Message message = handler.obtainMessage();
message.obj = downloadBitmap(imageUrl);
handler.sendMessage(message);
}
}.start();
return null;
}
public interface ImageCallBack {
void getBitmap(Bitmap bitmap);
}
// ----其它工具----------------------------------------------------------------------------------
private Bitmap downloadBitmap(String imageUrl) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(new URL(imageUrl).openStream());
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Bitmap drawable2Bitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
// canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
public static Drawable bitmap2Drable(Bitmap bm) {
return new BitmapDrawable(bm);
}
public static String getbase64(byte[] image) {
String string = "";
try {
base64Encoder encoder = new base64Encoder();
string = encoder.encodeBuffer(image).trim();
} catch (Exception e) {
e.printStackTrace();
}
return string;
}
@SuppressWarnings("deprecation")
public static Drawable byte2Drawable(byte[] imgByte) {
Bitmap bitmap;
if (imgByte != null) {
bitmap = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
Drawable drawable = new BitmapDrawable(bitmap);
return drawable;
}
return null;
}
public static byte[] bitmap2Byte(Bitmap bm) {
Bitmap outBitmap = Bitmap.createScaledBitmap(bm, 150, bm.getHeight() * 150 / bm.getWidth(), true);
if (bm != outBitmap) {
bm.recycle();
bm = null;
}
byte[] compressData = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
try {
outBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} catch (Exception e) {
e.printStackTrace();
}
compressData = baos.toByteArray();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return compressData;
}
public static Bitmap setBitmapSize(Bitmap bitmap, int newWidth, int newHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = (newWidth * 1.0f) / width;
float scaleHeight = (newHeight * 1.0f) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}
public static Bitmap setBitmapSize(String bitmapPath, float newWidth, float newHeight) {
Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath);
if (bitmap == null) {
Logger.i("bitmap", "bitmap------------>发生未知异常!");
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = newWidth / width;
float scaleHeight = newHeight / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// 原始图片的宽高
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// 在保证解析出的bitmap宽高分别大于目标尺寸宽高的前提下,取可能的inSampleSize的最大值
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
// 首先设置 inJustDecodeBounds=true 来获取图片尺寸
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 计算 inSampleSize 的值
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 根据计算出的 inSampleSize 来解码图片生成Bitmap
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static void compressBmpToFile(Bitmap bmp, File file) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 80;// 个人喜欢从80开始,
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
options -= 10;
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Bitmap compressImageFromFile(String srcPath, float pixWidth, float pixHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;// 只读边,不读内容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);
options.inJustDecodeBounds = false;
int w = options.outWidth;
int h = options.outHeight;
int scale = 1;
if (w > h && w > pixWidth) {
scale = (int) (options.outWidth / pixWidth);
} else if (w < h && h > pixHeight) {
scale = (int) (options.outHeight / pixHeight);
}
if (scale <= 0)
scale = 1;
options.inSampleSize = scale;// 设置采样率
options.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
options.inPurgeable = true;// 同时设置才会有效
options.inInputShareable = true;// 。当系统内存不够时候图片自动被回收
bitmap = BitmapFactory.decodeFile(srcPath, options);
// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
// 其实是无效的,大家尽管尝试
return bitmap;
}
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
}
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android图形与图像处理技巧总结》、《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。



