关于使用SDWebImage内存爆涨的问题

问题:控制器里下载N张图片,当图片过大(图片质量和尺寸)使用SDWebImage时,快速滑动页面进行加载会撑爆内存。很多博客都说使用如下方式,在合适的时机清除缓存来处理,然并卵。

[[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];

处理方式

UIImage+MultiFormat中修改方法+ (UIImage *)sd_imageWithData:(NSData *)data,根据图片的data得到图片的大小,判断大小超过一定阈值时对图片进行压缩——通过上下文重新绘制bitmap。

+(UIImage *)compressImageWith:(UIImage *)image {
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = 640;
    float height = (image.size.height * width) / image.size.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;
    
}

同时,在AppDelegate收到内存警告时处理:

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    [[SDWebImageManager sharedManager] cancelAll];
    [[SDWebImageManager sharedManager].imageCache clearMemory];
}

其它处理方式

如果不影响SD原有代码,可直接通过一个类别,对原有的sd_imageOrientationFromImageData方法和自定义的方法进行切换处理。

@implementation UIImage (SDImageCompress)
/**
 initialize方法会在所有的类加载完毕后 第一次向类发送消息的时候 会被调用
 
 这里并不能用load因为你不能确定哪个分类先加载完毕了,initialize的调用确保该类及其分类均已加载完毕,所以下面是可以拿到方法的指针。
 */
+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
        // 替换SD里面sd_imageWithData的方法为自己的方法
        Method originalMethod = class_getClassMethod(class, @selector(sd_imageWithData:));
        Method swizzledMethod = class_getClassMethod(class, @selector(customSd_imageWithData:));
        method_exchangeImplementations(originalMethod, swizzledMethod);
        
        // 因为sd_imageWithData里面回调sd里面自己的方法,然后通过自己写一个方法,再将该方法转回到sd里面
        Method originalMethod1 = class_getClassMethod(class, @selector(customSd_imageOrientationFromImageData:));
        Method swizzledMethod1 = class_getClassMethod(class, @selector(sd_imageOrientationFromImageData:));
        method_exchangeImplementations(originalMethod1, swizzledMethod1);
#pragma clang diagnostic pop
    });
}

/*
 sd内部处理下载完毕数据的方法
 
 * This file is part of the SDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

+ (nullable UIImage *)customSd_imageWithData:(nullable NSData *)data {
    if (!data) {
        return nil;
    }
    
    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];
        if (data.length > 128 * 1024) { // 大于128KB时进行压缩处理
           image = [self compressImageWith:image];
        }
        
        UIImageOrientation orientation = [self customSd_imageOrientationFromImageData:data];
        if (orientation != UIImageOrientationUp) {
            image = [UIImage imageWithCGImage:image.CGImage
                                        scale:image.scale
                                  orientation:orientation];
        }
    }
    return image;
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容