Resolving memory warning issues caused by sdwebimage loading large graphs in Mwphotobrowser

Source: Internet
Author: User


Mwphotobrowser is a very nice photo browser on GitHub's star close to 3,000, <a href= "Https://github.com/mwaterfall/MWPhotoBrowser.git" target= "_blank" title= "go to official website" >mwphotobrowser Download </a>

Mwphotobrowser to load small figure 1M The following should not have a memory warning issue. If you encounter large image, 3M, 4M, 5M large map, it is likely to lead to memory warning. I've been having this problem lately and it's a headache. Swipe back and forth to see the photo memory soar above 100M:



The online search of a lot of information, did not solve the problem.

Let's take a look at Mwphotobrowser, in fact Mwphotobrowser use is sdwebimage to download pictures. <a href= "Https://github.com/rs/SDWebImage.git" target= "_blank" title= "go to official website" >sdwebimage Download </a>

At GitHub, I saw Sdwebimage's introduction, which says:

    Future enhancements        LRU memory cache cleanup instead of the Reset on memory warning


See this really want to cry no tears AH.

Again to see Sdwebimage's, there is a personal question:

    How to disable "Memory cache"?  I don ' t want memory cache,  It used a lot of memory and got memory waring easily,  disk was enough for me ...


Someone replied:

    There is no-to-Disable the memory cache. But the cache was designed to flush itself if you get a memory warning, so you shouldn ' t need to worry it.


Say is Sdwebimage encounter memory warning will automatically free memory, but this can not solve the problem, load large image, the memory will suddenly jump to more than 100 m, on the 4s and below the phone to run, and then hung up.

There is still no problem solving the memory warning. What do we do?

That's how I solved it:

Sdwebimage has a sdwebimagedownloaderoperation class to perform the download operation. There's a way to do it in a download:

-(void) connectiondidfinishloading: (nsurlconnection *) aconnection {sdwebimagedownloadercompletedblock completionBl       Ock = Self.completedblock;           @synchronized (self) {cfrunloopstop (cfrunloopgetcurrent ());           Self.thread = nil;           Self.connection = nil;       [[Nsnotificationcenter Defaultcenter] postnotificationname:sdwebimagedownloadstopnotification Object:nil]; } if (![       [Nsurlcache Sharedurlcache] cachedresponseforrequest:_request]) {responsefromcached = NO; } if (Completionblock) {if (Self.options & Sdwebimagedownloaderignorecachedresponse &amp           ;& responsefromcached) {Completionblock (nil, nil, nil, YES);               } else {UIImage *image = [UIImage sd_imageWithData:self.imageData];               NSString *key = [[Sdwebimagemanager Sharedmanager] CacheKeyForURL:self.request.URL]; Image = [Self Scaledimageforkey:key image:imaGE]; Do not force decoding animated GIFs if (!image.images) {image = [UIImage Decodedimagew               Ithimage:image]; } if (Cgsizeequaltosize (Image.size, Cgsizezero)) {Completionblock (nil, nil, [Nserror Erro rwithdomain:@ "Sdwebimageerrordomain" code:0 Userinfo:@{nslocalizeddescriptionkey: @ "Downloaded image has 0 pixels"}],               YES);               } else {Completionblock (image, Self.imagedata, nil, YES);       }}} Self.completionblock = nil;    [self-done]; }


Wherein, UIImage *image = [UIImage sd_imageWithData:self.imageData]; is the conversion of data into an image.

And look at Sd_imagewithdata: This method:

+ (UIImage *) Sd_imagewithdata: (NSData *) data {       UIImage *image;       NSString *imagecontenttype = [NSData sd_contenttypeforimagedata:data];       if ([Imagecontenttype isequaltostring:@ "Image/gif"]) {           image = [UIImage sd_animatedgifwithdata:data];       }    #ifdef SD_WEBP       Else if ([Imagecontenttype isequaltostring:@ "IMAGE/WEBP"])       {           image = [UIImage sd_ Imagewithwebpdata:data];       }    #endif       else {           image = [[UIImage alloc] initwithdata:data];           Uiimageorientation orientation = [self sd_imageorientationfromimagedata:data];           if (orientation! = Uiimageorientationup) {               image = [UIImage imagewithcgimage:image. Cgimage                                           Scale:image.scale                                     orientation:orientation];           }       }       return image;    



This method in Uiimage+multiformat, is a category of uiimage processing. This sentence is important. image = [[UIImage alloc] initwithdata:data]; Sdwebimage the downloaded data directly into the image, and then does not do the same as the zoom directly saved up to use. So, we just need to do the processing here:

Uiimage+multiformat Add a method:

+ (UIImage *) Compressimagewith: (UIImage *) Image {Float imagewidth = image.size.width;       float imageheight = image.size.height;       float width = 640;       float height = image.size.height/(image.size.width/width);       float Widthscale = imagewidth/width;              float Heightscale = imageheight/height;              Create a bitmap context//and set it as the currently in use context Uigraphicsbeginimagecontext (cgsizemake (width, height));        if (Widthscale > Heightscale) {[Image drawinrect:cgrectmake (0, 0, Imagewidth/heightscale, height)];       } else {[Image drawinrect:cgrectmake (0, 0, Width, imageheight/widthscale)];       }//Create a resized image from the current context UIImage *newimage = Uigraphicsgetimagefromcurrentimagecontext ();              Make the current context out of the stack uigraphicsendimagecontext ();           return newimage; }



Then in: Image = [[UIImage alloc] initwithdata:data]; The following is called:

if (data.length/1024 > 1024x768) {               image = [self compressimagewith:image];           }


Compress when data is greater than 1M. The revolution is not yet successful and needs to be dealt with in one step. Inside the Connectiondidfinishloading method of the Sdwebimagedownloaderoperation:

UIImage *image = [UIImage sd_imageWithData:self.imageData];      will be equal than the compressed image in the transfer to data assigned to Self.imagedata      nsdata *data = uiimagejpegrepresentation (image, 1);      Self.imagedata =  [Nsmutabledata datawithdata:data];



Working Gaocheng, let's take a look at the effect:


?

Sure enough, the problem was solved.

For more iOS development-related technologies, please follow iOS development public number iOS:

Iosdevtip

Resolving memory warning issues caused by sdwebimage loading large graphs in Mwphotobrowser

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.