Cropping an image with imagepickercontroller in swift

Swift 4.0+

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    var image : UIImage!

    if let img = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
    {
        image = img

    }
    else if let img = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    {
        image = img
    }


    picker.dismiss(animated: true, completion: nil)
}

Don't forget to set allowsEditing to true.

Another option is to use TOCropViewController. Its does more with much less code. What I found good about it that it allows you to change the cropping rectangle.

class ViewController: UIViewController, CropViewControllerDelegate {

    ... //your viewcontroller code

    func presentCropViewController {
        let image: UIImage = ... //Load an image

        let cropViewController = CropViewController(image: image)
        cropViewController.delegate = self
        present(cropViewController, animated: true, completion: nil)
    }

    func cropViewController(_ cropViewController: CropViewController, 
         didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) {
        // 'image' is the newly cropped version of the original image
    }
}

You can use default controls to achieve image cropping.

self.imgPicker.allowsEditing = true

Delegate Method

//MARK: image picker delegate method
    //MARK:
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        var image : UIImage!

        if let img = info[UIImagePickerControllerEditedImage] as? UIImage
        {
            image = img

        }
        else if let img = info[UIImagePickerControllerOriginalImage] as? UIImage
        {
            image = img
        }


        picker.dismiss(animated: true,completion: nil)
 }

Tags:

Ios

Swift