Skip to content

Instantly share code, notes, and snippets.

@nbertagnolli
Created February 23, 2020 18:20
Show Gist options
  • Save nbertagnolli/eb82d914442a86f4cbb36dcaac2f943c to your computer and use it in GitHub Desktop.
Save nbertagnolli/eb82d914442a86f4cbb36dcaac2f943c to your computer and use it in GitHub Desktop.
Resize Image in Swift3
// Create a variable describing the desired dimensions of our image
private let trainedImageSize = CGSize(width: 64, height: 64)
// Taken from:
// https://stackoverflow.com/questions/31314412/how-to-resize-image-in-swift
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment