How to get the edited image from UIImagePickerController in Swift?

China☆狼群 提交于 2019-12-04 08:34:35

SWIFT 3.0:

Add UINavigationControllerDelegate and UIImagePickerControllerDelegate

var imagePicker = UIImagePickerController()

@IBAction func btnSelectPhotoOnClick(_ sender: UIButton)
{
    let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
        self.openCamera()
    }))

    alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
        self.openGallary()
    }))

    alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))

    imagePicker.delegate = self
    self.present(alert, animated: true, completion: nil)
}
func openCamera()
{
    if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
    {
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
    }
    else
    {
        let alert  = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}
func openGallary()
{
    imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
    imagePicker.allowsEditing = true
    self.present(imagePicker, animated: true, completion: nil)
}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    picker.dismiss(animated: true, completion: nil)
//You will get cropped image here..
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage
    {
        self.imageView.image = image
    }   
}

You can do it like this.

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

    let image = info[UIImagePickerControllerEditedImage] as UIImage
}

I found the cause of the issue! Its because of the property "allowsEditing" which was set to false! I have changed that to true and now it is working fine.

Swift 4.2

if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
        // Use editedImage Here
    }

Make sure you allowed to editing image in UIImagePickerController.

You can allow UIImagePickerController to edit the UIImage by making this

picker.allowsEditing = true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!