UIImage 占用内存大小

1、查看 AFNetworking 代码,里面的估算方法是

CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
    CGFloat bytesPerPixel = 4.0;
    CGFloat bytesPerRow = imageSize.width * bytesPerPixel; // 2560
    CGFloat totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerRow;
    NSLog(@"s1:%lu",(unsigned long)totalBytes); // 输出 10240

2、查看 CGImage 类,发现下面的方法:CGImageGetHeight和CGImageGetBytesPerRow。这样计算应该更准确

CGFloat cgImageBytesPerRow = CGImageGetBytesPerRow(image.CGImage); // 2560
    CGFloat cgImageHeight = CGImageGetHeight(image.CGImage); // 1137
    NSUInteger size  = cgImageHeight * cgImageBytesPerRow;
    NSLog(@"size:%lu",(unsigned long)size); // 输出 2910720

使用 Instruments 查看内存使用情况:


instrument.png

和输出保持一致。

3、搜索 stack overflow ,参考这里:

NSUInteger s1 = UIImagePNGRepresentation(thumbImage).length;
NSUInteger s2 = UIImageJPEGRepresentation(thumbImage, 1).length;
NSUInteger s3  = CGImageGetHeight(thumbImage.CGImage) * CGImageGetBytesPerRow(thumbImage.CGImage);
NSLog(@"s1:%u",s1); // s1 is the size of a .png image when saved to a file
NSLog(@"s2:%u",s2); // s2 is the size of a .jpg image when save to a file with best quality
NSLog(@"s3:%u",s3); // correct

你可能感兴趣的:(UIImage 占用内存大小)