Scaling and sizing an image

Image sizing in Swift

When you are uploading an image to the server you don’t want to upload HUGE images, so you will need to rescale the image but also watch out on the aspect ratio.

Here is a snippet that will show you how to rescale/resize an image:

 func scaleUIImageToSize(let image: UIImage, let size: CGSize) -> UIImage {
 let hasAlpha = true 
 let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
 UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
 image.drawInRect(CGRect(origin: CGPointZero, size: size))
 
 let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
 UIGraphicsEndImageContext()
 return scaledImage
}

 

Usage:

let scaledImg = self.scaleUIImageToSize(img, size: CGSizeMake(img.size.width/4, img.size.height/4)) // or whatever size you want to resize to

 

Leave a Reply

Your email address will not be published. Required fields are marked *