iOS 图片加载优化

最近阅读了一些大佬关于图片优化的博客,但是没有具体的demo,所以根据大佬提的优化方案,写了一个demo。
参考地址:https://www.jianshu.com/p/7d8a82115060?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

本demo使用了降采样和异步处理进行优化

1、降采样:
//UIKit方式
-(UIImage*)resizeUI:(CGSize)size{
    UIGraphicsBeginImageContextWithOptions(size, YES, 0);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
//CoreGraphics
-(UIImage*)resizeCG:(CGSize)size{
    CGImageRef cgImage = self.CGImage;
    if (cgImage == nil){
        return  nil;
    }
    size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage);
    size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);
    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(cgImage);
    
    CGContextRef context = CGBitmapContextCreate(nil, size.width, size.height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), cgImage);
    CGImageRef bitmapImageRef = CGBitmapContextCreateImage(context);
    UIImage *image = [UIImage imageWithCGImage:bitmapImageRef scale:self.scale orientation:self.imageOrientation];
    return image;
}
//ImageIO
- (UIImage*)resizeIO:(CGSize)size{
    NSData *data = UIImagePNGRepresentation(self);
    if (data == nil){
        return nil;
    }
    CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)data, nil);
    if (imageSource == nil) {
        return nil;
    }
    CFDictionaryRef property = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil);
    NSDictionary *propertys = CFBridgingRelease(property);
    CGFloat height = [propertys[@"PixelHeight"] integerValue]; //图像k宽高,12000
    CGFloat width = [propertys[@"PixelWidth"] integerValue];
    //以较大的边为基准
    int imageSize = (int)MAX(size.width, size.height);
    CFStringRef keys[5];
    CFTypeRef values[5];
    //创建缩略图等比缩放大小,会根据长宽值比较大的作为imageSize进行缩放
    //kCGImageSourceThumbnailMaxPixelSize为生成缩略图的大小。当设置为800,如果图片本身大于800*600,则生成后图片大小为800*600,如果源图片为700*500,则生成图片为800*500
    keys[0] = kCGImageSourceThumbnailMaxPixelSize;
    CFNumberRef thumbnailSize = CFNumberCreate(NULL, kCFNumberIntType, &imageSize);
    values[0] = (CFTypeRef)thumbnailSize;
    keys[1] = kCGImageSourceCreateThumbnailFromImageAlways;
    values[1] = (CFTypeRef)kCFBooleanTrue;
    keys[2] = kCGImageSourceCreateThumbnailWithTransform;
    values[2] = (CFTypeRef)kCFBooleanTrue;
    keys[3] = kCGImageSourceCreateThumbnailFromImageIfAbsent;
    values[3] = (CFTypeRef)kCFBooleanTrue;
    keys[4] = kCGImageSourceShouldCacheImmediately;
    values[4] = (CFTypeRef)kCFBooleanTrue;
    
    CFDictionaryRef options = CFDictionaryCreate(kCFAllocatorDefault, (const void **)keys, (const void **)values, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CGImageRef thumbnailImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options);
    UIImage *resultImg = [UIImage imageWithCGImage:thumbnailImage];
    return resultImg;
}
//CoreImage
- (UIImage*)resizeCI:(CGSize)size{
    CGImageRef cgImage = self.CGImage;
    if (cgImage == nil){
        return  nil;
    }
    CIImage *ciImageInput = [CIImage imageWithCGImage:cgImage];
    double scale = size.width/self.size.height;
    CIFilter *filter = [CIFilter filterWithName:@"CILanczosScaleTransform"];
    [filter setValue:ciImageInput forKey:kCIInputImageKey];
    [filter setValue:[NSNumber numberWithDouble:scale] forKey:kCIInputScaleKey];
    [filter setValue:@(1.0) forKey:kCIInputAspectRatioKey];
    CIImage *ciImageOutput = [filter valueForKey:kCIOutputImageKey];
    if (!ciImageOutput) {
        return nil;
    }
    CIContext *ciContext = [[CIContext alloc] initWithOptions:@{kCIContextUseSoftwareRenderer : @(NO)}];
    CGImageRef ciImageRef = [ciContext createCGImage:ciImageOutput fromRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *resultImg = [UIImage imageWithCGImage:ciImageRef];
    return  resultImg;
}
//vImage
- (UIImage*)resizeVI:(CGSize)size{
    CGImageRef cgImage = self.CGImage;
    if (cgImage == nil){
        return  nil;
    }

    vImage_CGImageFormat format;
    format.bitsPerComponent = 8;
    format.bitsPerPixel = 32; //ARGB四通道 4*8
    format.colorSpace = nil; //默认sRGB
    format.bitmapInfo = kCGImageAlphaFirst | kCGBitmapByteOrderDefault; // 表示ARGB
    format.version = 0;
    format.decode = nil; //默认色彩映射范围【0, 1.0】
    format.renderingIntent = kCGRenderingIntentDefault;//超出【0,1】范围后怎么处理
    //源图片buffer,输出图片buffer
    vImage_Buffer sourceBuffer, outputBuffer;
    vImage_Error error = vImageBuffer_InitWithCGImage(&sourceBuffer, &format, nil, cgImage, kvImageNoFlags);
    if (error != kvImageNoError) {
         return nil;
    }
    float scale = self.scale;
    int width = (int)size.width;
    int height = (int)size.height;
    int bytesPerPixel = (int)CGImageGetBitsPerPixel(cgImage)/8;
    //设置输出格式
    outputBuffer.width = width;
    outputBuffer.height = height;
    outputBuffer.rowBytes = bytesPerPixel * width;
    outputBuffer.data = malloc(outputBuffer.rowBytes * outputBuffer.height);
    //缩放到当前尺寸上
    error = vImageScale_ARGB8888(&sourceBuffer, &outputBuffer, nil, kvImageHighQualityResampling);
    if (error != kvImageNoError) {
          return nil;
    }
        
    CGImageRef outputImageRef = vImageCreateCGImageFromBuffer(&outputBuffer, &format, nil, nil, kvImageNoFlags, &error);
    UIImage *resultImg = [UIImage imageWithCGImage:outputImageRef];
    return  resultImg;
}

2、异步加载:
-(void)update:(NSIndexPath *)indexPath{
    NSURL *currentURL = [NSURL URLWithString:[self.imgURLArray objectAtIndex:indexPath.row]];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    __weak typeof(self) weakSelf = self;
    
    //异步下载图片
    dispatch_async(queue, ^{
        UIImage *images = [UIImage imageWithData:[NSData dataWithContentsOfURL:currentURL]];
        CGSize size = CGSizeMake(images.size.width/10, images.size.height/10);
        [images resizeCG:size];
        weakSelf.imgs[currentURL] = images;
        
        //更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            MyCollectionViewCell *cell = (MyCollectionViewCell *)[weakSelf.myCollectionView cellForItemAtIndexPath:indexPath];
            cell.image = images;
        });
    });
    self.tasks[currentURL] = queue;
}

demo地址:https://github.com/chenmengdi/load_image.git

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

推荐阅读更多精彩内容