Skip to content

Instantly share code, notes, and snippets.

@CavalcanteLeo
Forked from nicroth/Helper.m
Created March 22, 2016 02:52
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 CavalcanteLeo/d7bb5922041e4f288a52 to your computer and use it in GitHub Desktop.
Save CavalcanteLeo/d7bb5922041e4f288a52 to your computer and use it in GitHub Desktop.
iOS - Resize a UIImage - actually resizes the data for uploading!
//takes an image, and returns a dictionary with multiple sizes
-(NSDictionary *)resizeImage:(UIImage *)theImage
{
//Create the "large" size image to upload
float actualHeight = theImage.size.height;
float actualWidth = theImage.size.width;
float imgRatio = actualWidth/actualHeight;
//set the maximum size you want - width/height
float maxRatio = 640.0/960.0;
//determine the required size to use
if(imgRatio!=maxRatio){
if(imgRatio < maxRatio){
imgRatio = 960.0 / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = 960.0;
}
else{
imgRatio = 640.0 / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = 640.0;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
//createa a new graphics context
UIGraphicsBeginImageContext(rect.size);
[theImage drawInRect:rect];
//create a new UIImage to hold the "large" resize
UIImage *full = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Create the thumbnail image to upload
//the dance is very similar!
actualHeight = theImage.size.height;
actualWidth = theImage.size.width;
imgRatio = actualWidth/actualHeight;
maxRatio = 160.0/240.0;
if(imgRatio!=maxRatio){
if(imgRatio < maxRatio){
imgRatio = 240.0 / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = 240.0;
}
else{
imgRatio = 160.0 / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = 160.0;
}
}
rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[theImage drawInRect:rect];
//create a new UIIimage to hold the "thumb" size
UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:theImage, @"original", full, @"full", thumb, @"thumb" nil];
return dict;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment