Aaron Presley

← Writing
Resize UIImage Largest Side in Swift

July 6, 2016

I'm knee deep in Swift these days, and am working a lot with the UIImage object. I couldn't find a quick extension method that allowed me to resize an image based on the largest side, so I wrote one:

extension UIImage {
    func resizeLargestSide(largestSide:CGFloat) -> UIImage {

        var percentageDecrease:CGFloat
        var targetSize:CGSize

        // This is a landscape photo
        if self.size.width > self.size.height {

            // Calculate the percentage decrease
            percentageDecrease = (largestSide / self.size.width) * 100

            // Calculate the new height
            let newHeight = self.size.height * (percentageDecrease / 100)

            // Set our size
            targetSize = CGSize(width: largestSide, height: newHeight)

        // This is a portrait photo
        } else {

            // Calculate the percentage decrease
            percentageDecrease = (largestSide / self.size.height) * 100

            // Calculate the new width
            let newWidth = self.size.width * (percentageDecrease / 100)

            // Set our size
            targetSize = CGSize(width: newWidth, height: largestSide)
        }

        // Generate our new image
        UIGraphicsBeginImageContext(targetSize)
        self.drawInRect(CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height))
        let newImg = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImg
    }
}

You can use it like so:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    self.imagePicker.dismissViewControllerAnimated(true, completion: nil)

    // The image we just took
    var theImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    // Resizing the image's largest side to be 2000px wide
    theImage = theImage.resizeLargestSide(2000.0)

    // Converting it to NSData
    let imageData = NSData(data: UIImageJPEGRepresentation(theImage, 1.0)!)

    // ...more code here...
}

Good luck!