美文网首页
UIimage 内存占用问题

UIimage 内存占用问题

作者: changeWong | 来源:发表于2017-03-08 10:40 被阅读384次

    我们平时可能在写代码的时候,并没有在意UIimage对内存的占用问题。
    最近我在做项目的时候,需要对多个图片进行压缩处理,发现处理后内存并没有马上得到释放。然后在网上找到了一种方法,就是写在@autoreleasepool里面。代码如下:

    [imageArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary *dic = obj;
            @autoreleasepool {
                
                NSString *fbigPath = [dic[@"fbigpath"] lastPathComponent];
                NSString * fsmallPath = [dic[@"fsmallpath"] lastPathComponent];
                
                UIImage *bigImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:dic[@"fbigpath"]]]];
                [[FileManager shareFileManager] writeBig:UIImageJPEGRepresentation(bigImage, 1.0) andWithPath:fbigPath];
                
                //压缩大图
                NSData * tempData = UIImageJPEGRepresentation(bigImage, 1.0);
                UIImage * smallimage;
                UIImage * ComImage;
                
                if ((float)([tempData length] / 1000.0 / 1000.0) >= 0.05) {
                    
                    smallimage = [self imageCompressForWidth:bigImage targetWidth:300];
                    ComImage = smallimage;
                    NSData * reduceData = UIImageJPEGRepresentation(smallimage, 0.35);
                    
                    while ((float)([reduceData length] / 1000.0 / 1000.0) >= 0.05) {
                        
                        NSData * data = [NSData dataWithData:reduceData];
                        ComImage = [UIImage imageWithData:data];
                        [ComImage imageByResizeToSize:CGSizeMake(ComImage.size.width * 0.6, ComImage.size.height * 0.6)];
                        reduceData = UIImageJPEGRepresentation(ComImage, 1.0);
                    }
                } else {
                    ComImage = bigImage;
                }
    
                [[FileManager shareFileManager] writeSmall:UIImageJPEGRepresentation(ComImage, 1.0) andWithPath:fsmallPath];
                
                ComImage = nil;
                smallimage = nil;
                bigImage = nil;
            }
        }];
    

    在for循环里面,每次对image处理都放在autoreleasepool里面,然后在处理完后系统就会马上释放掉内存。

    相关文章

      网友评论

          本文标题:UIimage 内存占用问题

          本文链接:https://www.haomeiwen.com/subject/gtcbgttx.html