How to easily resize/optimize an image size with iOS?
A couple of suggestions are provided as answers to this question. I had suggested the technique described in this post, with the relevant code:
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;{ UIGraphicsBeginImageContext( newSize ); [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage;}
As far as storage of the image, the fastest image format to use with the iPhone is PNG, because it has optimizations for that format. However, if you want to store these images as JPEGs, you can take your UIImage and do the following:
NSData *dataForJPEGFile = UIImageJPEGRepresentation(theImage, 0.6);
This creates an NSData instance containing the raw bytes for a JPEG image at a 60% quality setting. The contents of that NSData instance can then be written to disk or cached in memory.
The easiest and most straightforward way to resize your images would be this
float actualHeight = image.size.height;float actualWidth = image.size.width;float imgRatio = actualWidth/actualHeight;float maxRatio = 320.0/480.0;if(imgRatio!=maxRatio){ if(imgRatio < maxRatio){ imgRatio = 480.0 / actualHeight; actualWidth = imgRatio * actualWidth; actualHeight = 480.0; } else{ imgRatio = 320.0 / actualWidth; actualHeight = imgRatio * actualHeight; actualWidth = 320.0; }}CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);UIGraphicsBeginImageContext(rect.size);[image drawInRect:rect];UIImage *img = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();
The above methods work well for small images, but when you try to resize a very large image, you will quickly run out of memory and crash the app. A much better way is to use CGImageSourceCreateThumbnailAtIndex
to resize the image without completely decoding it first.
If you have the path to the image you want to resize, you can use this:
- (void)resizeImageAtPath:(NSString *)imagePath { // Create the image source (from path) CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef) [NSURL fileURLWithPath:imagePath], NULL); // To create image source from UIImage, use this // NSData* pngData = UIImagePNGRepresentation(image); // CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)pngData, NULL); // Create thumbnail options CFDictionaryRef options = (__bridge CFDictionaryRef) @{ (id) kCGImageSourceCreateThumbnailWithTransform : @YES, (id) kCGImageSourceCreateThumbnailFromImageAlways : @YES, (id) kCGImageSourceThumbnailMaxPixelSize : @(640) }; // Generate the thumbnail CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options); CFRelease(src); // Write the thumbnail at path CGImageWriteToFile(thumbnail, imagePath);}
More details here.