iossdkimage-compressionuiimagejpegrepresentation

Image compression by size - iPhone SDK


I would like to compress images (camera/photo library) and then send it to the server. I know I can compress by height and width, but I would like to compress the images by size to a fixed size (200 KB) only and keep the original height and width. The scale factor in JPEGRepresentation does not represent the size and only compression quality. How can I achieve this (compress to a fixed size) without using any third party library?


Solution

  • Heres some example code that will attempt to compress an image for you so that it doesn't exceed either a max compression or maximum file size

    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    int maxFileSize = 250*1024;
    
    NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);
    
    while ([imageData length] > maxFileSize && compression > maxCompression)
    {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(yourImage, compression);
    }