Android开发之超强图片工具类BitmapUtil完整实例
短信预约 -IT技能 免费直播动态提醒
本文实例讲述了Android开发之超强图片工具类BitmapUtil。分享给大家供大家参考,具体如下:
说明:为了方便大家使用,本人把大家常用的图片处理代码集中到这个类里
使用了LruCache与SoftReference
public class BitmapUtil { private static Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>(); 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---------------------------------------------------- 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<Integer, Void, Bitmap> { 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<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap); // 添加该对象到Map中使其缓存 imageCache.put(path, softBitmap); } public static Bitmap getBitmapByPath(String path) { // 从缓存中取软引用的Bitmap对象 SoftReference<Bitmap> 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<Bitmap> 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>(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 class="lazy" data-srcPath, float pixWidth, float pixHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;// 只读边,不读内容 Bitmap bitmap = BitmapFactory.decodeFile(class="lazy" data-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(class="lazy" data-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; } }
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
Android开发之超强图片工具类BitmapUtil完整实例
下载Word文档到电脑,方便收藏和打印~
下载Word文档
猜你喜欢
Android开发之超强图片工具类BitmapUtil完整实例
本文实例讲述了Android开发之超强图片工具类BitmapUtil。分享给大家供大家参考,具体如下:说明:为了方便大家使用,本人把大家常用的图片处理代码集中到这个类里使用了LruCache与SoftReference/** * 图片加载及
2023-05-30
Android开发中日期工具类DateUtil完整实例
本文实例讲述了Android开发中日期工具类DateUtil。分享给大家供大家参考,具体如下:/** * 日期操作工具类. * @Project ERPForAndroid * @Package com.ymerp.android.to
2023-05-30
Android开发实现查询远程服务器的工具类QueryUtils完整实例
本文实例讲述了Android开发实现查询远程服务器的工具类QueryUtils。分享给大家供大家参考,具体如下:public class QueryUtils
2023-05-30
Android开发之多媒体文件获取工具类实例【音频,视频,图片等】
本文实例讲述了Android开发之多媒体文件获取工具类。分享给大家供大家参考,具体如下:package com.android.ocr.util;import java.io.File;import java.util.ArrayList;
2023-05-30