Created
August 3, 2012 16:08
-
-
Save nicroth/3249042 to your computer and use it in GitHub Desktop.
iOS - Resize a UIImage - actually resizes the data for uploading!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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