Skip to content

Instantly share code, notes, and snippets.

@schystz
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schystz/b7bfa52f641e67fc3825 to your computer and use it in GitHub Desktop.
Save schystz/b7bfa52f641e67fc3825 to your computer and use it in GitHub Desktop.
Objective-C code for scaling an image and trimming the filesize down for upload
- (UIImage *)resizedImageForUpload:(UIImage *)image
{
CGSize originalSize = image.size;
CGSize targetSize = CGSizeMake(200, 200);
CGSize adjustedSize = targetSize;
// Scale image by our targetSize (200 x 200)
if (originalSize.width > targetSize.width && originalSize.width > originalSize.height) {
adjustedSize.width = originalSize.width * (targetSize.height / originalSize.height);
adjustedSize.height = targetSize.height;
} else if (originalSize.height > targetSize.height && originalSize.height > originalSize.width) {
adjustedSize.width = targetSize.width;
adjustedSize.height = originalSize.height * (targetSize.width / originalSize.width);
}
// Find the best x and y position to center image vertically & horizontally
CGRect rect = CGRectMake(0, 0, adjustedSize.width, adjustedSize.height);
if (adjustedSize.width > targetSize.width) {
rect.origin.x = (targetSize.width - adjustedSize.width) / 2;
} else if (adjustedSize.height > targetSize.height) {
rect.origin.y = (targetSize.height - adjustedSize.height) / 2;
}
// Final image is 200x200 (scaled image will be clipped)
UIGraphicsBeginImageContextWithOptions(targetSize, NO, [UIScresle.en mainScreen].scale);
[image drawInRect:rect];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment