SDWebImage(5.0.0) 加载大图内存崩溃问题

网上的思路基本就是把下载的图片进行压缩,但是我这边遇到点问题,一个是网上的基本是老版本的SDWebImage,我用的5.0.0的不太适用,再一个就是用的pod,直接在源码更改不太理想。

我这边的解决思路就是找到SDWebImage下载图片的方法对下载完的图片进行压缩,当然实现方式使用runtime的swizzledSelector,这样不用改动源码。

SDWebImage下载图片的方法

网上查了一些关于SDWebImage(5.0.0)源码解析的资料,最后基本定位在这个两个方法

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

- (void)callCompletionBlocksWithImage:(nullable UIImage *)image
                            imageData:(nullable NSData *)imageData
                                error:(nullable NSError *)error
                             finished:(BOOL)finished

hook一个类中的实例方法

这里贴一下代码

+ (void)swizzlingInClass:(Class)cls originalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector
{
    Class class = cls;
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    if (!originalMethod || !swizzledMethod) {
        return;
    }

    IMP originalIMP = method_getImplementation(originalMethod);
    IMP swizzledIMP = method_getImplementation(swizzledMethod);
    const char *originalType = method_getTypeEncoding(originalMethod);
    const char *swizzledType = method_getTypeEncoding(swizzledMethod);

    class_replaceMethod(class,swizzledSelector,originalIMP,originalType);
    class_replaceMethod(class,originalSelector,swizzledIMP,swizzledType);
}

这里是具体实现

创建SDWebImageDownloaderOperation一个分类做hook,代码供参考

#import "SDWebImageDownloaderOperation.h"
NS_ASSUME_NONNULL_BEGIN


@interface SDWebImageDownloaderOperation (HDImageCompressHook)

@end

NS_ASSUME_NONNULL_END
#import "SDWebImageDownloaderOperation+HDImageCompressHook.h"
#import "HDBJHookTool.h"

@implementation SDWebImageDownloaderOperation (HDImageCompressHook)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL originalSelector1 = @selector(URLSession: task: didCompleteWithError:);
        SEL swizzledSelector1 = @selector(hd_URLSession: task: didCompleteWithError:);
        [HDBJHookTool swizzlingInClass:[self class] originalSelector:originalSelector1 swizzledSelector:swizzledSelector1];
        [HDBJHookTool swizzlingInClass:[self class] originalSelector:originalSelector1 swizzledSelector:swizzledSelector1];
        
        SEL originalSelector2 = @selector(callCompletionBlocksWithImage:
                                          imageData:
                                          error:
                                          finished:);
        SEL swizzledSelector2 = @selector(hd_callCompletionBlocksWithImage:
                                          imageData:
                                          error:
                                          finished:);
        [HDBJHookTool swizzlingInClass:[self class] originalSelector:originalSelector2 swizzledSelector:swizzledSelector2];
    });
}
#pragma mark - Method Swizzling
- (void)hd_URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{

    Ivar ivar1 = class_getInstanceVariable([self class], "_imageData");
    if (object_getIvar(self, ivar1)) {
        NSMutableData * imageData = (NSMutableData *)object_getIvar(self, ivar1);
        NSData *imgData = UIImageJPEGRepresentation([UIImage imageWithData:[imageData copy]],1);
        NSUInteger sizeOriginKB = imageData.length / 1024;
         if (sizeOriginKB > 500){
            imgData = UIImageJPEGRepresentation([UIImage imageWithData:[imageData copy]],0.1);
            [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
        }
//        imgData = [self resetSizeOfImageData:[UIImage imageWithData:[imageData copy]] maxSize:50];
        
        if (imgData.length/1024 > 200) {
            UIImage *image = [self compressImageWith:[UIImage imageWithData:imgData]];
            imgData = UIImagePNGRepresentation(image);
            MyLog(@"didCompleteWithError---------%ld",imgData.length/1024);
            if (imgData.length/1024 > 200) {
                imageData = [NSMutableData dataWithData:[self resetSizeOfImageData:image maxSize:90]];
                MyLog(@"didCompleteWithErrorresetSizeOfImageData---------%ld",imageData.length/1024);
            }
        }
        imageData = [NSMutableData dataWithData:imgData];
        object_setIvar(self, ivar1, imageData);
    }
    [self hd_URLSession:session task:task didCompleteWithError:error];
}

- (void)hd_callCompletionBlocksWithImage:(nullable UIImage *)image
                               imageData:(nullable NSData *)imageData
                                   error:(nullable NSError *)error
                                finished:(BOOL)finished{
    NSUInteger sizeOriginKB = imageData.length / 1024;
    if (sizeOriginKB > 500){
        imageData = UIImageJPEGRepresentation(image,0.1);
        image = [UIImage imageWithData:imageData];
    }
//    imageData = [self resetSizeOfImageData:image maxSize:90];
    image = [UIImage imageWithData:imageData];
    if (imageData.length/1024 > 200) {
        image = [self compressImageWith:image];
        imageData = UIImagePNGRepresentation(image);
        MyLog(@"hd_callCompletionBlocksWithImage---------%ld",imageData.length/1024);
        if (imageData.length/1024 > 200) {
            imageData = [self resetSizeOfImageData:image maxSize:90];
            image = [UIImage imageWithData:imageData];
            MyLog(@"hd_callCompletionBlocksWithImageresetSizeOfImageData---------%ld",imageData.length/1024);
        }
    }
    
    [self hd_callCompletionBlocksWithImage:image
                                 imageData:imageData
                                     error:error
                                  finished:finished];
}
-(UIImage *)compressImageWith:(UIImage *)image{
    
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = 320;
    float height = image.size.height/(image.size.width/width);
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的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)];
    }
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    return newImage;
}
#pragma mark - 图片压缩
- (NSData *)resetSizeOfImageData:(UIImage *)sourceImage maxSize:(NSInteger)maxSize {
    //先判断当前质量是否满足要求,不满足再进行压缩
    __block NSData *finallImageData = UIImageJPEGRepresentation(sourceImage,1.0);
    NSUInteger sizeOrigin   = finallImageData.length;
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB <= maxSize) {
        return finallImageData;
    }
    
    //获取原图片宽高比
    CGFloat sourceImageAspectRatio = sourceImage.size.width/sourceImage.size.height;
    //先调整分辨率
    CGSize defaultSize = CGSizeMake(1024, 1024/sourceImageAspectRatio);
    UIImage *newImage = [self newSizeImage:defaultSize image:sourceImage];
    
    finallImageData = UIImageJPEGRepresentation(newImage,1.0);
    
    //保存压缩系数
    NSMutableArray *compressionQualityArr = [NSMutableArray array];
    CGFloat avg   = 1.0/250;
    CGFloat value = avg;
    for (int i = 250; i >= 1; i--) {
        value = i*avg;
        [compressionQualityArr addObject:@(value)];
    }
    
    /*
     调整大小
     说明:压缩系数数组compressionQualityArr是从大到小存储。
     */
    //思路:使用二分法搜索
    finallImageData = [self halfFuntion:compressionQualityArr image:newImage sourceData:finallImageData maxSize:maxSize];
    //如果还是未能压缩到指定大小,则进行降分辨率
    while (finallImageData.length == 0) {
        //每次降100分辨率
        CGFloat reduceWidth = 100.0;
        CGFloat reduceHeight = 100.0/sourceImageAspectRatio;
        if (defaultSize.width-reduceWidth <= 0 || defaultSize.height-reduceHeight <= 0) {
            break;
        }
        defaultSize = CGSizeMake(defaultSize.width-reduceWidth, defaultSize.height-reduceHeight);
        UIImage *image = [self newSizeImage:defaultSize
                                      image:[UIImage imageWithData:UIImageJPEGRepresentation(newImage,[[compressionQualityArr lastObject] floatValue])]];
        finallImageData = [self halfFuntion:compressionQualityArr image:image sourceData:UIImageJPEGRepresentation(image,1.0) maxSize:maxSize];
    }
    return finallImageData;
}
#pragma mark 调整图片分辨率/尺寸(等比例缩放)
- (UIImage *)newSizeImage:(CGSize)size image:(UIImage *)sourceImage {
    CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
    
    CGFloat tempHeight = newSize.height / size.height;
    CGFloat tempWidth = newSize.width / size.width;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
    } else if (tempHeight > 1.0 && tempWidth < tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
#pragma mark 二分法
- (NSData *)halfFuntion:(NSArray *)arr image:(UIImage *)image sourceData:(NSData *)finallImageData maxSize:(NSInteger)maxSize {
    NSData *tempData = [NSData data];
    NSUInteger start = 0;
    NSUInteger end = arr.count - 1;
    NSUInteger index = 0;
    
    NSUInteger difference = NSIntegerMax;
    while(start <= end) {
        index = start + (end - start)/2;
        
        finallImageData = UIImageJPEGRepresentation(image,[arr[index] floatValue]);
        
        NSUInteger sizeOrigin = finallImageData.length;
        NSUInteger sizeOriginKB = sizeOrigin / 1024;
//        NSLog(@"当前降到的质量:%ld", (unsigned long)sizeOriginKB);
//        NSLog(@"\nstart:%zd\nend:%zd\nindex:%zd\n压缩系数:%lf", start, end, (unsigned long)index, [arr[index] floatValue]);
        
        if (sizeOriginKB > maxSize) {
            start = index + 1;
        } else if (sizeOriginKB < maxSize) {
            if (maxSize-sizeOriginKB < difference) {
                difference = maxSize-sizeOriginKB;
                tempData = finallImageData;
            }
            if (index<=0) {
                break;
            }
            end = index - 1;
        } else {
            break;
        }
    }
    return tempData;
}
@end

主要的压缩图片代码是这里

NSUInteger sizeOriginKB = imageData.length / 1024;
    if (sizeOriginKB > 500){
        imageData = UIImageJPEGRepresentation(image,0.1);
        image = [UIImage imageWithData:imageData];
    }
//    imageData = [self resetSizeOfImageData:image maxSize:90];
    image = [UIImage imageWithData:imageData];
    if (imageData.length/1024 > 200) {
        image = [self compressImageWith:image];
        imageData = UIImagePNGRepresentation(image);
        MyLog(@"hd_callCompletionBlocksWithImage---------%ld",imageData.length/1024);
        if (imageData.length/1024 > 200) {
            imageData = [self resetSizeOfImageData:image maxSize:90];
            image = [UIImage imageWithData:imageData];
            MyLog(@"hd_callCompletionBlocksWithImageresetSizeOfImageData---------%ld",imageData.length/1024);
        }
    }

这些压缩图片的方法是网上找的,在使用- (NSData *)resetSizeOfImageData:(UIImage *)sourceImage maxSize:(NSInteger)maxSize 这个方法直接压缩比较大的图片时比较慢,最后使用了现在这种多级判断压缩图片来实现。

大概就是这么一个思路了谁有更好的方法也可提供一下。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,657评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,662评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,143评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,732评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,837评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,036评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,126评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,868评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,315评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,641评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,773评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,859评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,584评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,676评论 2 351

推荐阅读更多精彩内容