How to select a portion of an image, crop, and save it using Swift?

Using Swift 3

Image cropping can be done using CGImages from CoreGraphics.

Get the CGImage version of a UIImage like this:

// cgImage is an attribute of UIImage
let cgImage = image.cgImage

CGImage objects have a method cropping(to: CGRect) that does the cropping:

let croppedCGImage: CGImage = cgImage.cropping(to: toRect)

Finally, convert back from CGImage to UIImage:

let uiImage = UIImage(cgImage: croppedCGImage)

Example function:

func cropImage(image: UIImage, toRect: CGRect) -> UIImage? {
    // Cropping is available trhough CGGraphics
    let cgImage :CGImage! = image.cgImage
    let croppedCGImage: CGImage! = cgImage.cropping(to: toRect)

    return UIImage(cgImage: croppedCGImage)
}

The CGRect attribute of cropping defines the 'crop rectangle' inside the image that will be cropped.


https://github.com/myang-git/iOS-Image-Crop-View does something like what you are looking for..

Hope this helps.


Found one more solution. This time it is in Swift. The solution looks elegant and the code relative to other such solutions is written in fewer number of lines.

Here it is.. https://github.com/DuncanMC/CropImg Thanks to Duncan Champney for making his work available on github.