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.
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.
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)];
lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(highResImage, quality)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With