下面两种现象,用同一种方法解决

1、解决MWPhotoBrowser中的SDWebImage加载大图导致的内存警告问题

2、突然有一天首页访问图片很慢,至少隔20多秒所有图片才会出来。(解析:app使用了SDWebImage的sd_setImageWithURL获取图片,SDWebImage获取图片的原理是先从本地缓存获取,如果没有从本地磁盘获取,如果没有再根据url从网络获取。具体可查看 http://www.cnblogs.com/Kingly/p/5235004.html ,通过跟踪代码,问题出在从本地磁盘获取banner图片时很慢,好像阻止了所有线程继续获取图片,通过检查banner图片得知,其中有2张图片的大小超过6M,SDWebImage从本地磁盘获取这么大的图片时非常慢且阻止了其他线程从本地磁盘获取图片。把banner的图片换成小些的图片就解决了。)

MWPhotoBrowser是一个非常不错的照片浏览器,在github的star接近3000个,地址:https://github.com/mwaterfall/MWPhotoBrowser.git

MWPhotoBrowser来加载小图1M以下的都应该不会有内存警告的问题。如果遇到大图,3M、4M、5M的大图,很有可能导致内存警告。最近我就遇到这个问题,很是头疼。来回滑动查看照片内存飙到100M以上:

我们来看一下MWPhotoBrowser,其实MWPhotoBrowser用的是SDWebImage来下载图片的。地址:https://github.com/rs/SDWebImage.git

在github看到SDWebImage的介绍,后面说到:

Future Enhancements

  • LRU memory cache cleanup instead of reset on memory warning

看到这个真是欲哭无泪啊。

再去看看SDWebImage的,有个人提问了:

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

有人回答:

There is no way to disable the memory cache. But the cache is designed to flush itself when you get a memory warning, so you shouldn't need to worry it.

说的是SDWebImage遇到内存警告会自动释放内存,但是这还是解决不了问题,加载大图的时候,内存会突然蹦到100多M,在4s及以下的手机上跑,再就挂了。

还是没有解决内存警告的问题。怎么办呢?

我是这么解决的:

SDWebImage有一个SDWebImageDownloaderOperation类来执行下载操作的。里面有个下载完成的方法:

  1. - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
  2. SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock;
  3. @synchronized(self) {
  4. CFRunLoopStop(CFRunLoopGetCurrent());
  5. self.thread = nil;
  6. self.connection = nil;
  7. [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
  8. }
  9.  
  10. if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) {
  11. responseFromCached = NO;
  12. }
  13.  
  14. if (completionBlock)
  15. {
  16. if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) {
  17. completionBlock(nil, nil, nil, YES);
  18. }
  19. else {
  20. UIImage *image = [UIImage sd_imageWithData:self.imageData];
  21. NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
  22. image = [self scaledImageForKey:key image:image];
  23.  
  24. // Do not force decoding animated GIFs
  25. if (!image.images) {
  26. image = [UIImage decodedImageWithImage:image];
  27. }
  28. if (CGSizeEqualToSize(image.size, CGSizeZero)) {
  29. completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code: userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES);
  30. }
  31. else {
  32. completionBlock(image, self.imageData, nil, YES);
  33. }
  34. }
  35. }
  36. self.completionBlock = nil;
  37. [self done];
  38. }

其中,UIImage *image = [UIImage sd_imageWithData:self.imageData];就是将data转换成image。

再看看sd_imageWithData:这个方法:

  1. + (UIImage *)sd_imageWithData:(NSData *)data {
  2. UIImage *image;
  3. NSString *imageContentType = [NSData sd_contentTypeForImageData:data];
  4. if ([imageContentType isEqualToString:@"image/gif"]) {
  5. image = [UIImage sd_animatedGIFWithData:data];
  6. }
  7. #ifdef SD_WEBP
  8. else if ([imageContentType isEqualToString:@"image/webp"])
  9. {
  10. image = [UIImage sd_imageWithWebPData:data];
  11. }
  12. #endif
  13. else {
  14. image = [[UIImage alloc] initWithData:data];
  15. UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
  16. if (orientation != UIImageOrientationUp) {
  17. image = [UIImage imageWithCGImage:image.CGImage
  18. scale:image.scale
  19. orientation:orientation];
  20. }
  21. }
  22.  
  23. return image;
  24. }

这个方法在UIImage+MultiFormat里面,是UIImage的一个类别处理。这句话很重要image = [[UIImage alloc] initWithData:data]; SDWebImage把下载下来的data直接转成image,然后没做等比缩放直接存起来使用。所以,我们只需要在这边做处理即可:

UIImage+MultiFormat添加一个方法:

  1. +(UIImage *)compressImageWith:(UIImage *)image
  2. {
  3. float imageWidth = image.size.width;
  4. float imageHeight = image.size.height;
  5. float width = ;
  6. float height = image.size.height/(image.size.width/width);
  7.  
  8. float widthScale = imageWidth /width;
  9. float heightScale = imageHeight /height;
  10.  
  11. // 创建一个bitmap的context
  12. // 并把它设置成为当前正在使用的context
  13. UIGraphicsBeginImageContext(CGSizeMake(width, height));
  14.  
  15. if (widthScale > heightScale) {
  16. [image drawInRect:CGRectMake(, , imageWidth /heightScale , height)];
  17. }
  18. else {
  19. [image drawInRect:CGRectMake(, , width , imageHeight /widthScale)];
  20. }
  21.  
  22. // 从当前context中创建一个改变大小后的图片
  23. UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  24. // 使当前的context出堆栈
  25. UIGraphicsEndImageContext();
  26.  
  27. return newImage;
  28.  
  29. }

然后在:image = [[UIImage alloc] initWithData:data];下面调用以下:

  1. if (data.length/ > ) {
  2. image = [self compressImageWith:image];
    data = UIImageJPEGRepresentation(image, 1.0);
  1. }

当data大于1M的时候做压缩处理。革命尚未成功,还需要一步处理。在SDWebImageDownloaderOperation的connectionDidFinishLoading方法里面的:

  1. UIImage *image = [UIImage sd_imageWithData:self.imageData];
  2.  
  3. //将等比压缩过的image在赋在转成data赋给self.imageData
  4. NSData *data = UIImageJPEGRepresentation(image, );
  5. self.imageData = [NSMutableData dataWithData:data];

内存降下来了,大功告成!

解决MWPhotoBrowser中的SDWebImage加载大图导致的内存警告问题的更多相关文章

  1. iOS SDWebImage加载大图导致内存崩溃解决方案

    static BOOL SDImageCacheOldShouldDecompressImages = YES; static BOOL SDImagedownloderOldShouldDecomp ...

  2. 解决hibernate中的懒加载(延迟加载)问题

    解决hibernate中的懒加载(延迟加载)问题   我们在开发的时候经常会遇到延迟加载问题,在实体映射时,多对一和多对多中,多的一样的属性默认是lazy="true"(即,默认是 ...

  3. 解决tableView中cell动态加载控件的重用问题

    解决tableView中cell动态加载控件的重用问题 tableView的cell,有时候需要在运行时取得对应的数据后才能够动态的创建该cell中的控件并加载到该cell中,此时,你一定会遇到重用问 ...

  4. 使用SDWebImage加载大量图片后造成内存泄露的解决办法

    SDWebImage的知名度就不用说了,github上近10k的star,国内外太多的App使用其进行图片加载. 但是最近在使用过程中发现,在UITableView中不断加载更多的内容,使用SDWeb ...

  5. Android中一张图片加载后所占用内存大小的获取与测试

    Android程序中一旦加载的图片比较多,就有可能出现Out of Memory而导致程序崩溃.这个一方面是因为Android系统本身对于每个单独的进程有内存大小的限制(有16M,64M,128M,2 ...

  6. java类中属性的加载顺序,以及内存分配情况介绍

    看下面例子及说明: /** 假如有外部类调用了该类,代码为:new StaticTest(); 那么下面是类属性的加载顺序 */ public class StaticTest{ public int ...

  7. Spring解决Hibernate中的懒加载问题

    OpenSessionInViewFilter 过滤器将 Hibernate Session 绑定到请求线程中,它将自动被 Spring 的事务管理器探测到. <filter>       ...

  8. 前不久一个swift项目用uicollectionview 用sdwebimage 加载图片,发生内存猛增,直接闪退的情况,简单说一下解决方案。

    1.首先在appdelegate方法 didFinishLaunchingWithOptions SDImageCache.sharedImageCache().maxCacheSize=1024*1 ...

  9. vs中 VMDebugger未能加载导致异常

    ,纠结了许久的一个问题,终于找到了解决 vs中 VMDebugger未能加载导致异常 错误号:80004005 搜了好多,没有一个给出完美的答案.   解决办法:工具->导入和导出设置,重置一下 ...

随机推荐

  1. Java基础知识学习(五)

    高级特性:接口 接口(Interface) 1) 接口中只能定义抽象方法,默认为 public abstract 的,变量可以是static的 2) 接口中没有构造方法 3) 一个接口不实现另一个接口 ...

  2. 修改Mac系统的默认截图保存路径到指定目录

    注:此文仅针对mac系统如果你是mac用户,会发现桌面经常一团糟,桌面到处都是平时的截图(mac系统的截图是command+shift+3 和 command+shift+4 两个快捷命令) 之前一直 ...

  3. Asp.net MVC验证哪些事(3)-- Remote验证及其改进(附源码)

    表单中的输入项,有些是固定的,不变的验证规则,比如字符长度,必填等.但有些是动态的,比如注册用户名是否存在这样的检查,这个需要访问服务器后台才能解决.这篇文章将会介绍MVC中如何使用[RemoteAt ...

  4. Android搭建junit测环境

    在AndroidManifest.xml文件中增加两个东西,分别是: 1.uses-library ,位于application里面. 2.instrumentation,与application同级 ...

  5. SqlServer链接MySql操作步骤

    Sql Server版本 2008R2 1.从MySQL网站下载最新的MySQL ODBC驱动:http://www.mysql.com/downloads/connector/odbc/,我下载的版 ...

  6. c# 请求api获得json数据

    public static string HttpGet(string Url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Creat ...

  7. sqlyog不用密码登陆(强制取消)

    1.启用命令行.cd ../返回磁盘根目录.输入D: 进入D盘.dir可以显示所以文件夹. 2.在D盘找到mysql安装目录的bin文件夹 cd /xampp/mysql/bin 3.然后输入命令'm ...

  8. Linux 多线程条件变量同步

    条件变量是线程同步的另一种方式,实际上,条件变量是信号量的底层实现,这也就意味着,使用条件变量可以拥有更大的自由度,同时也就需要更加小心的进行同步操作.条件变量使用的条件本身是需要使用互斥量进行保护的 ...

  9. Toritoisegit记住用户名密码

    TortoiseGit每次连接git都得输入密码了,如果我们用到的比较频繁这样是很麻烦的,那么下面我们来看一篇关于window设置TortoiseGit连接git不用每次输入用户名和密码的配置,具体的 ...

  10. Struts2文件上传,以及各种注意事项

    首先肯定是要配置好struts2环境,这个在另一篇<struts2环境搭建,以及一个简单实例>里已经讲过了 首先是网页部分,upload_file.jsp <%@ page lang ...