Search code examples
swiftuiimageuiimagepickercontrollercropcgimage

Cropping UIImage fails


I'm trying to crop an image from UIImagePicker to a specific rect, but I receive dark colors instead of an image (which seems to be the color themes of the image).

First my imagePicker function:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
         let originalImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        imagePicker.dismiss(animated: true, completion: nil)
        if originalImage == nil { print("Error Not Found An Image")}
            imageView.image = originalImage
            let croppedImage = cropImage(image: originalImage, rect: CGRect(x: 0.13, y: 0.12, width: 0.74, height: 0.75))
            imageView.image = croppedImage
}

And my crop function

    func cropImage (image: UIImage, rect: CGRect) -> UIImage {

        let resImage = CIImage(image: image, options: [:])
        let croppedImage = resImage?.cropped(to: rect)
        let img = UIImage(ciImage: croppedImage!, scale: 1, orientation: image.imageOrientation)

        return img
    }

Solution

  • The problem was with the values of the rect. In my case they were simply too small.

    Thanks badhanganesh for the hint