Android client load network big picture How to avoid memory overflow

Source: Internet
Author: User

When loading large images on SDcard to memory in Android development is prone to oom exceptions, a common workaround is to define the specified decoding method based on the methods provided by the Bitmapfactory.options class .设置inJustDecodeBounds属性为true,避免分配内存,返回一个null的Bitmap对象(包含outWidth,outHeightandoutMimeType),然后读取图片的尺寸和类型。再根据屏幕的高和宽对图片进行缩放,最后将缩放的图片加载到内存,主要代码如下:

1Options opts =NewOptions ();2Opts.injustdecodebounds =true;//set to True, the loader does not return a picture, but instead sets the field in the options object that begins with out. That's just decoding the edge area.3 Bitmapfactory.decodefile (FilePath, opts);4         5         //get the width and height of the picture6         intImageWidth =Opts.outwidth;7         intImageHeight =Opts.outheight;8         9         //get the width and height of the screenTenDisplay display = This. Getwindowmanager (). Getdefaultdisplay ();//Get the default form display object One         intScreenWidth =display.getwidth (); A         intScreenHeight =display.getheight (); -          -         //Calculating the zoom ratio the         intWidthscale = imagewidth/ScreenWidth; -         intHeightscale = imageheight/ScreenHeight; -          -         intScale = Widthscale > Heightscale?Widthscale:heightscale; -          +          //specifies that the load can be loaded out of the picture. AOpts.injustdecodebounds =false; at         //scale with calculated scale -Opts.insamplesize =Scale ; -Bitmap BM =bitmapfactory.decodefile (path, opts);

This code is mainly for users stored on the sdcard on the big picture, if you want to get a large picture from the network and display on the Android, how should avoid Oom exception?

First load the network big picture if it is through the Bitmapfactory.decodestream (InputStream) method, there will be a memory overflow, so we can also consider using the options class to scale the image processing, The network picture Stream object is then loaded with the Bitmapfactory.decodestream (IS, outpadding, opts) method, but the options scale is determined if the direct write options.insamplesize = fixed value There are two problems: first, if the fixed value is too small, there is a possibility of memory overflow, and the second is if the fixed value is too large to cause the image to be loaded blurred, so now the same consideration is based on the height and width of the image and the height and width of the screen to zoom? But the pictures have not yet loaded out how to get the picture high and wide? You might think that by putting the optionsthe. Injustdecodebounds is set to True, then Bitmapfactory.decodestream (IS, outpadding, options) are called, and then the options. outwidth; and options.outheight; get the picture high and wide, the idea is good, but when you calculate the zoom ratio again by options.injustdecodebounds = False;options.insamplesize = Scale Bitmap BM = Bitmapfactory.decodestream (IS, outpadding, options) method gets the zoomed picture when you see what's on the phone interface, and then look at the log to find the output line Skimagedecoder:: Factory returned null information, returned unexpectedly is empty object, depressed bar, this is why? You used the Bitmapfactory.decodestream (is, outpadding, options) method two times in the code, and further said that you used the same InputStream stream object two times. The start position of the second use of stream has been moved to the end, so the return is empty, then what to do? My current approach is to open two stream objects individually, one for setting the options scale, one for Bitmapfactory.decodestream (IS, outpadding, options) method calls, After testing I found that if you first set options and then passed to Bitmapfactory.decodestream will be very card, picture long time load not come out, so I changed a way: first through the httpclient to get a picture of the stream object, get its width and height according to the width of the screen to calculate the scale; Then through the httpclient to get the picture of the stream object, based on the calculated scaling scale, the main code is as follows:

    /*** Calculate the zoom ratio of the picture *@return     */     Public intGetscare () {Try{HttpClient Client=Newdefaulthttpclient (); HttpGet HttpGet=NewHttpGet (IMAGEURL); HttpResponse Response=Client.execute (HttpGet); intCode =response.getstatusline (). Getstatuscode (); if(200 = =code) {InputStream is=response.getentity (). getcontent (); Options opts=NewOptions (); Opts.injustdecodebounds=true; Bitmapfactory.decodestream (IS,NULL, opts); intImageWidth =Opts.outwidth; intImageHeight =Opts.outheight; Display Display= Imageactivity. This. Getwindowmanager (). Getdefaultdisplay (); intScreenWidth =display.getwidth (); intScreenHeight =display.getheight (); intWidthscale = imagewidth/ScreenWidth; intHeightscale = imageheight/ScreenHeight; intScale = Widthscale > Heightscale?Widthscale:heightscale; returnScale ; }        } Catch(Exception e) {e.printstacktrace (); }        return1;//default 1 When network connection fails}
/*** Get network pictures*/    protected voidGetnetimage () {Try{HttpClient Client=Newdefaulthttpclient (); HttpGet HttpGet=NewHttpGet (IMAGEURL); HttpResponse Response=Client.execute (HttpGet); intCode =response.getstatusline (). Getstatuscode (); if(200 = =code) {InputStream is=response.getentity (). getcontent (); Options opts=NewOptions (); //scale based on calculated proportions                intScale =Getscare (); Opts.insamplesize=Scale ; Bitmap BM= Bitmapfactory.decodestream (IS,NULL, opts); //takes bm to the main thread for displaying pictures, updating the UIMessage msg =Message.obtain (); Msg.obj=BM;            Handler.sendmessage (msg); }        } Catch(Exception e) {e.printstacktrace (); }    }
// Show Pictures    New Handler () {        publicvoid  handlemessage (Message msg) {            = ( Bitmap) Msg.obj;            Iv.setimagebitmap (BM);     };

Android client load network big picture How to avoid memory overflow

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.