Friday, February 28, 2014

Compressing Photos/UIImage maintaining Aspect Ratio in iPhone App

Normally, the pictures taken from iPhone camera are high resolutions and it ranges from 1-4 MB in size. When our app needs to send these size of images to the server, upload may take long time which  breaks down the overall app's performance. So in this section, I am sharing a short and sweat objective-c method which will compress original image in iPhone , makes image size small and also the aspect ratio is maintained.
As for my test, 2048*1536 (930 kb) size image  is compressed to 600*450 (169 kb) image and 2448*3264 (2.5 mb) size image is compressed to 600*800 (230 kb) image using the following objective-c method:

- (UIImage *)compressImage:(UIImage *)image {
    float actualHeight = image.size.height;
    float actualWidth = image.size.width;
    float maxHeight = 800.0; //new max. height for image
    float maxWidth = 600.0; //new max. width for image
    float imgRatio = actualWidth/actualHeight;
    float maxRatio = maxWidth/maxHeight;
    float compressionQuality = 0.5; //50 percent compression
   
    if (actualHeight > maxHeight || actualWidth > maxWidth){
        if(imgRatio < maxRatio){
            //adjust width according to maxHeight
            imgRatio = maxHeight / actualHeight;
            actualWidth = imgRatio * actualWidth;
            actualHeight = maxHeight;
        }
        else if(imgRatio > maxRatio){
            //adjust height according to maxWidth
            imgRatio = maxWidth / actualWidth;
            actualHeight = imgRatio * actualHeight;
            actualWidth = maxWidth;
        }
        else{
            actualHeight = maxHeight;
            actualWidth = maxWidth;
        }
    }
    NSLog(@"Actual height : %f and Width : %f",actualHeight,actualWidth);
    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [image drawInRect:rect];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
    UIGraphicsEndImageContext();
   
    return [UIImage imageWithData:imageData];
}

* depending on your compressionQuality , the image size and quality varies, and its value ranger from 0 to 1.

1 comment:

  1. Very impressive post! Compressive photos and image feature will resolve your memory issues some how. YoTurf app is an iOS app 2014 developed by Crackheads for introverts. Available at app store for downloading.

    ReplyDelete