This article describes the powerful image tool BitmapUtil, which is developed by Android. Share it for your reference, as follows:
Note: In order to facilitate everyone's use, I have concentrated the commonly used image processing codes in this class
LruCache and SoftReference are used
/** * Image loading and conversion tools --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- How much memory does the system allocate to each application? The memory occupied by Bitmap is: the total number of pixels * * Memory occupied by each pixel. In Android, Bitmap has four pixel types: ARGB_8888, ARGB_4444, ARGB_565, and ALPHA_8. The number of bytes each pixel occupies is 4, 2, 2, and 1 respectively. Therefore, a 2000*1000 ARGB_8888 * The memory occupied by type Bitmap is 2000*1000*4=8000000B=8MB. * * @author * */ public class BitmapUtil { /** * 1) Soft reference is no longer suitable for cache image information, and overlap will occur when loading images * 2) In Android 3.0 (API Level 11), the data of the picture will be stored in local memory * Therefore, it cannot be released in a foreseeable way, which has the potential risk of causing the application to overflow and crash. * 3) Since Android 2.3 (API Level 9), garbage collectors will be more inclined to recycle objects that hold soft or weak references. This makes soft and weak citations no longer reliable. * */ private static Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>(); /** * Initialize lrucache, use the first to remove it at least, and LruCache is used to cache images. * When the storage Image size is greater than the value set by LruCache, the system will automatically release the memory. */ private static LruCache<String, Bitmap> mMemoryCache; static { final int memory = (int) (().maxMemory() / 1024); final int cacheSize = memory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { protected int sizeOf(String key, Bitmap value) { // return () / 1024; return () * (); } }; } // ---lrucache---------------------------------------------------- /** * Add image to lrucache * * @param key * @param bitmap */ public synchronized void addBitmapToMemCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { if (key != null & bitmap != null) { (key, bitmap); } } } /** * Clear cache */ public void clearMemCache() { if (mMemoryCache != null) { if (() > 0) { (); } mMemoryCache = null; } } /** * Remove cache */ public synchronized void removeMemCache(String key) { if (key != null) { if (mMemoryCache != null) { Bitmap bm = (key); if (bm != null) (); } } } /** * Read pictures from lrucache * * @param key * @return */ public Bitmap getBitmapFromMemCache(String key) { if (key != null) { return (key); } return null; } /** * Loading pictures * * @param context * @param resId * @param imageView */ public void loadBitmap(Context context, int resId, ImageView imageView) { final String imageKey = (resId); final Bitmap bitmap = getBitmapFromMemCache(imageKey); if (bitmap != null) { (bitmap); } else { (resId); BitmapWorkerTask task = new BitmapWorkerTask(context); (resId); } } /** * Task category * * @Project App_View * @Package * @author chenlin * @version 1.0 * @Date May 10, 2014 */ class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> { private Context mContext; public BitmapWorkerTask(Context context) { mContext = context; } // Load the picture in the background. @Override protected Bitmap doInBackground(Integer... params) { final Bitmap bitmap = decodeSampledBitmapFromResource((), params[0], 100, 100); addBitmapToMemCache((params[0]), bitmap); return bitmap; } } // --Soft Quotations ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- public static void addBitmapToCache(String path) { // Strongly referenced Bitmap object Bitmap bitmap = (path); // Soft referenced Bitmap object SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap); // Add this object to the map to cache it (path, softBitmap); } public static Bitmap getBitmapByPath(String path) { // Get soft referenced Bitmap object from cache SoftReference<Bitmap> softBitmap = (path); // Determine whether there is a soft reference if (softBitmap == null) { return null; } // Get out the Bitmap object. If the Bitmap is recycled due to insufficient memory, it will be empty Bitmap bitmap = (); return bitmap; } public Bitmap loadBitmap(final String imageUrl, final ImageCallBack imageCallBack) { SoftReference<Bitmap> reference = (imageUrl); if (reference != null) { if (() != null) { return (); } } final Handler handler = new Handler() { public void handleMessage(final msg) { // Add to cache Bitmap bitmap = (Bitmap) ; (imageUrl, new SoftReference<Bitmap>(bitmap)); if (imageCallBack != null) { (bitmap); } } }; new Thread() { public void run() { Message message = (); = downloadBitmap(imageUrl); (message); } }.start(); return null; } public interface ImageCallBack { void getBitmap(Bitmap bitmap); } // ---Other tools --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /** * Download pictures from the Internet * * @param imageUrl * @return */ private Bitmap downloadBitmap(String imageUrl) { Bitmap bitmap = null; try { bitmap = (new URL(imageUrl).openStream()); return bitmap; } catch (Exception e) { (); return null; } } /** * drawable to bitmap * * @param drawable * @return */ public static Bitmap drawable2Bitmap(Drawable drawable) { Bitmap bitmap = ((), (), () != ? .ARGB_8888 : .RGB_565); Canvas canvas = new Canvas(bitmap); // (bitmap); (0, 0, (), ()); (canvas); return bitmap; } /** * bitmap to drawable * * @param bm * @return */ public static Drawable bitmap2Drable(Bitmap bm) { return new BitmapDrawable(bm); } /** * Convert byte array into strings through BASE64Encoder * * @param image * @return */ public static String getBase64(byte[] image) { String string = ""; try { BASE64Encoder encoder = new BASE64Encoder(); string = (image).trim(); } catch (Exception e) { (); } return string; } /** * Convert byte data to Drawable * * @param imgByte * Byte data * @return */ @SuppressWarnings("deprecation") public static Drawable byte2Drawable(byte[] imgByte) { Bitmap bitmap; if (imgByte != null) { bitmap = (imgByte, 0, ); Drawable drawable = new BitmapDrawable(bitmap); return drawable; } return null; } /** * Convert the image into a byte array * * @param bmp * @return */ public static byte[] bitmap2Byte(Bitmap bm) { Bitmap outBitmap = (bm, 150, () * 150 / (), true); if (bm != outBitmap) { (); bm = null; } byte[] compressData = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { try { (, 100, baos); } catch (Exception e) { (); } compressData = (); (); } catch (IOException e) { (); } return compressData; } /** * Zoom picture * * @param bitmap * Original picture * @param newWidth * @param newHeight * @return */ public static Bitmap setBitmapSize(Bitmap bitmap, int newWidth, int newHeight) { int width = (); int height = (); float scaleWidth = (newWidth * 1.0f) / width; float scaleHeight = (newHeight * 1.0f) / height; Matrix matrix = new Matrix(); (scaleWidth, scaleHeight); return (bitmap, 0, 0, width, height, matrix, true); } /** * Zoom picture * * @param bitmapPath * Image path * @return */ public static Bitmap setBitmapSize(String bitmapPath, float newWidth, float newHeight) { Bitmap bitmap = (bitmapPath); if (bitmap == null) { ("bitmap", "bitmap--------------->Unknown exception occurred!"); return null; } int width = (); int height = (); float scaleWidth = newWidth / width; float scaleHeight = newHeight / height; Matrix matrix = new Matrix(); (scaleWidth, scaleHeight); return (bitmap, 0, 0, width, height, matrix, true); } /** * Calculate the zoom size of the picture. If ==1, it means that there is no change. ==2, it means that the width and height are twice reduced -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * inSampleSize is a parameter of the class, which is int type, and its value indicates the multiple of pixel reduction in both length and width when parsing the picture as Bitmap. The default and minimum value of inSampleSize is 1 (when it is less than 1, the decoder treats this value as 1). * And when greater than 1, the value can only be a power of 2 (when it is not a power of 2, the decoder will take the power of 2 that is closest to the value). For example, when inSampleSize is 2, a 2000*1000 image will be reduced to 1000*500. Accordingly, its pixel count and memory usage will be reduced to 1/4 of the original: * * @param options * @param reqWidth * @param reqHeight * @return */ public static int calculateInSampleSize( options, int reqWidth, int reqHeight) { // The width and height of the original picture final int height = ; final int width = ; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // On the premise that the parsed bitmap width and height are greater than the target size width and height, take the maximum possible inSampleSize value under the premise that the parsed bitmap width and height are respectively greater than the target size width and height. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } /** * Generate Bitmap based on the calculated inSampleSize (the bitmap is a zoomed picture) * * @param res * @param resId * @param reqWidth * @param reqHeight * @return */ public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First set inJustDecodeBounds=true to get the image size final options = new (); /** * If the inJustDecodeBounds property is set to true, the decodeResource() method will not generate a Bitmap object, but will only read the size and type information of the image: */ = true; (res, resId, options); // Calculate the value of inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode the image based on the calculated inSampleSize to generate Bitmap = false; return (res, resId, options); } /** * When saving the image locally, compress it, that is, when changing the image from Bitmap to File form, * Features are: The image in the form of File is indeed compressed, but when you re-read the compressed file as Bitmap, the memory it takes up has not changed. * * @param bmp * @param file */ public static void compressBmpToFile(Bitmap bmp, File file) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int options = 80;// Personally, I like it starting from 80, (, options, baos); while (().length / 1024 > 100) { (); options -= 10; (, options, baos); } try { FileOutputStream fos = new FileOutputStream(file); (()); (); (); } catch (Exception e) { (); } } /** * When reading the image from local to memory, compress it, that is, the image changes from File form to Bitmap form * Features: By setting the sampling rate, reduce the pixels of the picture, and compress the Bitmap in memory * @param srcPath * @return */ public static Bitmap compressImageFromFile(String srcPath, float pixWidth, float pixHeight) { options = new (); = true;// Read only edges, not content Bitmap bitmap = (srcPath, options); = false; int w = ; int h = ; int scale = 1; if (w > h && w > pixWidth) { scale = (int) ( / pixWidth); } else if (w < h && h > pixHeight) { scale = (int) ( / pixHeight); } if (scale <= 0) scale = 1; = scale;// Set the sampling rate = Config.ARGB_8888;// This mode is default, no = true;// Setting will be effective = true;// . Pictures are automatically recycled when the system memory is insufficient bitmap = (srcPath, options); // return compressBmpFromBmp(bitmap);//The original method called this method to attempt to perform secondary compression // It's actually invalid, just try it return bitmap; } /** * Determine the angle of the photo * @param path * @return */ public static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = ( 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) { (); } return degree; } /** * Android has different single application memory sizes allocated to the system according to the device screen size and dpi. The following table * * Screen size DPI application memory * small/normal/large ldpi/mdpi 16MB * small/normal/large tvdpi/hdpi 32MB * small/normal/large xhdpi 64MB * small/normal/large 400dpi 96MB * small/normal/large xxhdpi 128MB * ------------------------------------------------------- * xlarge mdpi 32MB * xlarge tvdpi/hdpi 64MB * xlarge xhdpi 128MB * xlarge 400dpi 192MB * xlarge xxhdpi 256MB */ }
For more information about Android related content, please check out the topic of this site:Summary of Android graphics and image processing skills》、《Android development introduction and advanced tutorial》、《Android debugging skills and solutions to common problems》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary》
I hope this article will be helpful to everyone's Android programming design.