Arsad Arsad - 1 year ago 69
Objective-C Question

Shrink image without affecting the quality in objective c

How to shrink the image without affecting the quality programmatically.

After capture the image I want to reduce the size of that image without changing the quality in objective-c.

Answer Source

Here is the code I have used compress the image

Code :

-(UIImage *)compressImage:(UIImage *)image{

    NSData *imgData = UIImageJPEGRepresentation(image, 1); //1 it represents the quality of the image.
    NSLog(@"Size of Image(bytes):%ld",(unsigned long)[imgData length]);

    float actualHeight = image.size.height;
    float actualWidth = image.size.width;
    float maxHeight = 600.0;
    float maxWidth = 800.0;
    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;
            actualHeight = maxHeight;
            actualWidth = maxWidth;

    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
    [image drawInRect:rect];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);

    NSLog(@"Size of Image(bytes):%ld",(unsigned long)[imageData length]);

    return [UIImage imageWithData:imageData];

So Here is the code to use the above

UIImage *org = [UIImage imageNamed:@"MacLehose Stage 7 Stunning Natural Sceneries.jpg"];

UIImage *imgCompressed = [self compressImage:org];

If you want to compress more

NSData *dataImage = UIImageJPEGRepresentation(imgCompressed, 0.0);

NSLog(@"Size of Image(bytes):%ld",(unsigned long)[dataImage length]);

By the above mentioned way I am able to compress the image from 2 MB to near about 50 KB

Hope this helps

Happy coding ...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download