Android comes with the processing of bitmap out Memory, third party open source that is more convenient, the practice of their own words is still very good

Source: Internet
Author: User

/** * @author [email protected] * @time 20140606 * * Package Com.intbird.utils;import Java.lang.ref.weakreference;i Mport Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmap.config;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.paint;import Android.graphics.porterduff.mode;import Android.graphics.porterduffxfermode;import Android.graphics.Rect;import Android.graphics.drawable.bitmapdrawable;import Android.graphics.drawable.drawable;import Android.media.thumbnailutils;import Android.os.asynctask;import Android.widget.imageview;public class BitmapHelper {Private CacheManager cachemanager;public static final int img_type_res=0;public static final int img_type_web=1;public s tatic Final int img_type_file=3;private Bitmap bmpholder=null;private Bitmap bmpnoimg=null;public bitmaphelper (Context Context,int loadingid,int loadnoid) {cachemanager=cachemanager.getinstance (); bmpholder= Bitmapfactory.decoderesource (cOntext.getresources (), loadingid); Bmpnoimg=bitmapfactory.decoderesource (Context.getresources (), loadNoId);} /** * Load Picture * @param type network file, local file, or resource file * @param fileUrl URL * @param imageView control * @param width to get the specified height * @param heig HT to get the specified width */public void commonloadbitmap (int type,string fileurl,imageview imageview,int width,int height) {// No pictures in memory and files, re-acquired; Bitmap Bmp=cachemanager.getbitmapfromcache (FILEURL); if (bmp!=null) {imageview.setimagebitmap (BMP);} Else{switch (type) {case Img_type_web:loadmultibitmapfromweb (FILEURL, imageview,width,height); Break;case IMG_TYPE_ FILE:imageView.setImageBitmap (Getbitmapformfile (fileUrl, width, height, true)); Break;case Img_type_res: Imageview.setimageresource (Integer.parseint (FILEURL));  /** * Set ImageView to get the specified width of the specified file address of the image specified height; * @param fileUrl file address * @param reqwidth target width * @param reqheight target Height * @return Bitmap */public bitmap loadsinglebitmapfrom File (String fileurl,imageview iv,int reqwidth,int reqheight) {bitmapfactory.options options=new BitmapFactory. Options (); Options.injustdecodebounds=true;options.insamplesize=calculateinsamplesize (options, Reqwidth, Reqheight); Bitmapfactory.decodefile (fileurl,options); options.injustdecodebounds=false; Bitmap Bmp=bitmapfactory.decodefile (fileurl,options); if (iv!=null) iv.setimagebitmap (BMP); return bmp;} /** * Set ImageView as a network image that needs to be loaded; * @param WEBURL * @param imageView * @param width * @param heigth */public void Loadsinglebitmapfromweb (String weburl,imag Eview imageview,int width,int heigth) {bitmaphelper.bitmapworkersingletask task=new BitmapWorkerSingleTask (imageView ); Task.execute (weburl,width+ "", heigth+ "");} /** * Adapter Loading picture * @param fileUrl image address * @param imageView picture control * @param width to get the height of the */public voi to @param height D loadmultibitmapfromweb (String fileUrl, ImageView imageview,int width,int height) {if (Cancelpotentialwork (FILEURL, I                Mageview) {Final Bitmapmultiworkertask task = new Bitmapmultiworkertask (ImageView); Final asyncdrawable asyncdrawable =new asYncdrawable (Bmpholder, Task);                Imageview.setimagedrawable (asyncdrawable);    Task.execute (fileurl,width+ "", height+ ""); }}/** * Load a required bitmap from the network; * @param WEBURL * @param reqwidth * @param reqheight * @return */public Bitmap getbitmapformweb (String weburl,int reqwidth , int reqheight) {bitmapfactory.options options=new bitmapfactory.options (); Options.injustdecodebounds=true;o Ptions.insamplesize=calculateinsamplesize (Options, Reqwidth, reqheight); return Conninternet.loadbitmapfromnet ( WEBURL, options);} /** * Convert picture file to bitmap * * @param fileUrl * picture file path * @param width * Width * @param height * high  Degrees * @param isthumbnail * Whether to generate thumbnails based on aspect * @return */public Bitmap getbitmapformfile (String fileUrl, int width, int Height,boolean isthumbnail) {Bitmap bitmap=loadsinglebitmapfromfile (fileurl,null, width, height);//Generate a fixed-size thumbnail if ( Isthumbnail) {bitmap = Thumbnailutils.extractthumbnail (bitmap, Width, height,thumbnailutils.options_recycle_iNput);} Cachemanager.addbitmaptocache (FileUrl, bitmap); return bitmap;} /** * Convert picture into circle * * @param bitmap * @return */public static bitmap Changebitmaptoround (bitmap bitmap) {if (bitmap==null) RET Urn Null;int width = bitmap.getwidth (); int height = bitmap.getheight (); float roundpx;float left, top, right, bottom, dst_l EFT, Dst_top, Dst_right, dst_bottom;if (width <= height) {roundpx = Width/2;left = 0;top = 0;right = Width;bottom = W Idth;height = Width;dst_left = 0;dst_top = 0;dst_right = Width;dst_bottom = width;} else {roundpx = height/2;float clip = (width-height)/2;left = Clip;right = Width-clip;top = 0;bottom = Height;widt H = height;dst_left = 0;dst_top = 0;dst_right = Height;dst_bottom = height;} Bitmap output = bitmap.createbitmap (width, height, config.argb_8888); Canvas canvas = new canvas (output), final int color = 0xff424242;final Paint paint = new paint (); final rect src = new rect ( (int) left, (int) top, (int.) right, (int) bottom); final rect dst = new rect ((int) Dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);p Aint.setantialias (TRUE);//Set Brush non-aliased canvas.drawargb (0, 0, 0, 0); Fills the entire canvaspaint.setcolor (color);//The following two methods are used to draw the circle, Drawrounrect and drawcircle//canvas.drawroundrect (RECTF, ROUNDPX, ROUNDPX, paint);////draws a rounded rectangle, the first parameter is a graphic display area, the second parameter and the third parameter are the horizontal fillet radius and the vertical fillet radius, respectively. Canvas.drawcircle (ROUNDPX, ROUNDPX, ROUNDPX, paint);p Aint.setxfermode (New Porterduffxfermode (mode.src_in));// Set the pattern at which two pictures intersect, refer to Http://trylovecatch.iteye.com/blog/1189452canvas.drawBitmap (bitmap, SRC, DST, paint); Merge bitmap and Circlereturn output with draw in mode.src_in mode;} /** * Calculate the required size of the picture compression ratio * @param options * @param reqwidth required Width * @param reqheight Required Height * @return Compression ratio */public int Calcula    Teinsamplesize (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; while ((halfheight/insamplesize) > Reqheight && (halfwidth/insamplesize) > Reqwidth) {in    SampleSize *= 2; }}return Insamplesize;} /** * Check startup Task * @param fileUrl file path * @param imageView Target Control * @return whether to start Load task */private Boolean cancelpotentialwork (stri        Ng FileUrl, ImageView ImageView) {final Bitmapmultiworkertask bitmapworkertask = Getbitmapworkertask (ImageView);        if (bitmapworkertask! = null) {String bitmapurl = Bitmapworkertask.fileurl;            if (bitmapurl!=null&&bitmapurl! = fileUrl) {Bitmapworkertask.cancel (true);        return true;        } else {return false; }} return true; /** * Gets the load task in the picture control * @param ImageView * @return Returns the task */private Bitmapmultiworkertask getbitmapworkertask (ImageView imag       Eview) {if (ImageView! = null) {final drawable drawable = imageview.getdrawable (); if (drawable instanceof asyncdrawable) {final AsyNcdrawable asyncdrawable = (asyncdrawable) drawable;       return Asyncdrawable.getbitmapworkertask (); }} return null;} Private class Asyncdrawable extends Bitmapdrawable {private final weakreference<bitmapmultiworkertask> Bitmapwor    Kertaskreference; @SuppressWarnings ("deprecation") public asyncdrawable (Bitmap bitmap,bitmapmultiworkertask bitmapworkertask) {super (        Bitmap);    Bitmapworkertaskreference =new weakreference<bitmapmultiworkertask> (bitmapworkertask);    } public Bitmapmultiworkertask Getbitmapworkertask () {return bitmapworkertaskreference.get (); }}private class Bitmapmultiworkertask extends Asynctask<string, Void, bitmap> {private weakreference< imageview> imageviewreference;private String fileurl;public bitmapmultiworkertask (ImageView ImageView) { Imageviewreference=new weakreference<imageview> (ImageView);} @Overrideprotected Bitmap doinbackground (String ... params) {Fileurl=params[0];int Reqwidth=integeR.valueof (params[1]); int reqheight=integer.valueof (params[2]); Bitmap Bitmap=getbitmapformweb (fileurl,reqwidth,reqheight); return Bitmap;}        @Override protected void OnPostExecute (Bitmap Bitmap) {if (iscancelled ()) {Bitmap = null;                        } if (imageviewreference! = null) {final ImageView ImageView = Imageviewreference.get ();                       Final Bitmapmultiworkertask bitmapworkertask =getbitmapworkertask (ImageView); if (this = = Bitmapworkertask && ImageView! = null) {if (bitmap!=null) {Imagevie            W.setimagebitmap (bitmap);            Cachemanager.addbitmaptocache (FileUrl, bitmap);            } else{Imageview.setimagebitmap (bmpnoimg); }}}}}/** * Asynchronously loads a picture * @author [email protected] * */private class Bitmapworkersingletask Exte NDS asynctask<string, Void, Bitmap>{private Weakreference<imageview> imageviewreference;private String fileurl= "";p ublic bitmapworkersingletask (ImageView ImageView) { Imageviewreference=new weakreference<imageview> (ImageView);} @Overrideprotected Bitmap doinbackground (String ... params) {Fileurl=params[0];int reqwidth=integer.valueof (params[1 ]); int reqheight=integer.valueof (params[2]); Bitmap Bitmap=getbitmapformweb (fileurl,reqwidth,reqheight); return Bitmap;} @Overrideprotected void OnPostExecute (Bitmap Bitmap) {if (imageviewreference! = null) {final ImageView Imagev            Iew = Imageviewreference.get ();            if (ImageView! = null) {if (bitmap!=null) {imageview.setimagebitmap (bitmap);            } else{Imageview.setimagebitmap (bmpnoimg); }            }    }}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.