Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress UIImage

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.

like image 269
user2868048 Avatar asked Dec 04 '13 23:12

user2868048


3 Answers

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.

like image 198
Kunal Balani Avatar answered Sep 29 '22 19:09

Kunal Balani


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)];
like image 28
Matteo Gobbi Avatar answered Sep 29 '22 20:09

Matteo Gobbi


lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(highResImage, quality)];
like image 31
user3358463 Avatar answered Sep 29 '22 21:09

user3358463