Reputation: 6547
I would like to resize a UIImage to be able to upload it to parse.com. I would like to resize it without squashing it. How can I make sure that it is small enough to upload to parse.com (10485760 bytes) but not squash it to a set size. This is the code I tried below but obviously sets the image size exactly. Any ideas?
var newSize:CGSize = CGSize(width: 600,height: 600)
let rect = CGRectMake(0,0, newSize.width, newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
// image is a variable of type UIImage
profileImage?.drawInRect(rect)
profileImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Upvotes: 1
Views: 729
Reputation: 37300
Try using this method to scale your image while maintaining the aspect ratio:
func scaleImage(image: UIImage, maxDimension: CGFloat) -> UIImage {
var scaledSize = CGSize(width: maxDimension, height: maxDimension)
var scaleFactor: CGFloat
if image.size.width > image.size.height {
scaleFactor = image.size.height / image.size.width
scaledSize.width = maxDimension
scaledSize.height = scaledSize.width * scaleFactor
} else {
scaleFactor = image.size.width / image.size.height
scaledSize.height = maxDimension
scaledSize.width = scaledSize.height * scaleFactor
}
UIGraphicsBeginImageContext(scaledSize)
image.drawInRect(CGRectMake(0, 0, scaledSize.width, scaledSize.height))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
In this case, you would call it like so:
profileImage = scaleImage(profileImage, newSize: CGSizeMake(600, 600))
Upvotes: 3