When i am using UIImagePNGRepresentation or UIImageJPEGRepresentation for converting UIImage into NSdata, the image size is too much increased

前端 未结 1 1414
余生分开走
余生分开走 2020-12-10 03:46

When i am using UIImagePNGRepresentation or UIImageJPEGRepresentation for converting UIImage into NSdata, the image size is too much increased.

St

相关标签:
1条回答
  • 2020-12-10 04:28

    "hero_ipad_retina.jpg" is a compressed jpg image

    This line:

    [[NSData dataWithContentsOfFile:path] length]/1024
    

    gives it's compressed file size...

    This line:

    [UIImagePNGRepresentation(img) length]/1024
    

    uncompresses the image and converts it to PNG which is a lossless file format. It's size is inevitably much larger.

    This line:

    [UIImageJPEGRepresentation(img, 1.0) length]/1024  
    

    uncompresses the image and recompresses it to a JPG representation. You have set the quality to maximum (1.0) so - in comparison with the original which was no doubt compressed to lower quality - you get a larger file size. If you set quality to 0.5 you will get a small file size (around 42K)

    This is a great reminder of why you should treat jpeg images with caution. Every time you access a jpeg imageRep, you are uncompressing. If you then recompress - even at full quality - you are downgrading the quality of the image (as each lossy compress is worse than the previous). Artefacts increase and become particularly noticeable with graphic images (flat colours, straight/contrasting edges). PNG is always safer - it is lossless at 24-bit, and at 8-bit is good at dealing with regions of flat colour.

    update

    To get the size of an image in memory:

    NSUInteger sizeInBytes  = 
      CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);
    

    From this you can work out the compression ratios for PNG, JPG and the original file (divide by 1024 for kilobytes to get the correct ratios with the above figures).

    0 讨论(0)
提交回复
热议问题