Compress UIImage

14,976

Solution 1

Not quite sure if you want to resize or compress or both.

Below is the code for just compression :

Use JPEG Compression in two simple steps:

1) Convert UIImage to NSData

UIImage *rainyImage =[UImage imageNamed:@"rainy.jpg"];
NSData *imgData= UIImageJPEGRepresentation(rainyImage,0.1 /*compressionQuality*/);

this is lossy compression and image size is reduced.

2) Convert back to UIImage;

UIImage *image=[UIImage imageWithData:imgData];

For scaling you can use answer provided by Matteo Gobbi. But scaling might not be a the best alternative. You would rather prefer to have a thumbnail of the actual image by compression because scaling might make look your image bad on a retina display device.

Solution 2

lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(highResImage, quality)];

Solution 3

I wrote this function to scale an image:

- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {
    CGSize actSize = image.size;
    float scale = actSize.width/actSize.height;

    if (scale < 1) {
        newSize.height = newSize.width/scale;
    } else {
        newSize.width = newSize.height*scale;
    }


    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

The use is easy, for example:

[self scaleImage:yourUIImage toSize:CGMakeSize(300,300)];
Share:
14,976

Related videos on Youtube

user2868048
Author by

user2868048

Updated on July 12, 2022

Comments

  • user2868048
    user2868048 almost 2 years

    I need help resizing a UIImage.

    For example: I'm displaying a lot images in a UICollection View, but the size of those images is 2 to 4 MB. I need compress or resize those images.

    I found this: How to compress/resize image on iPhone OS SDK before uploading to a server? but I don't understand how to implement it.

    • Connor
      Connor over 10 years
      It would help if you provide some code showing what you've tried so far.
    • Rob
      Rob over 10 years
      If you're addressing memory usage when your collection view has many images open at the same time, then you want to focus on resizing, not compression (because compression affects the persistent memory storage, not the memory usage). This is a resizing routine that I use: stackoverflow.com/a/10491692/1271826