Search code examples
iosswiftxcodeuiimageuiimageorientation

Swift: UIImage orientation problem when applying filter in swift


I want to convert an image to grayscale by CIPhotoEffectNoir, but after using it, the image rotates. I searched a lot but the answers can not solve my problem.

This is my code:

    func grayscale(image: UIImage) -> UIImage? {
        let context = CIContext(options: nil)
        if let filter = CIFilter(name: "CIPhotoEffectNoir") {
            filter.setValue(CIImage(image: image), forKey: kCIInputImageKey)
            
            if let output = filter.outputImage {
                if let cgImage = context.createCGImage(output, from: output.extent) {
                    return UIImage(cgImage: cgImage)
                }
            }
        }
        return nil
    }

before:

enter image description here

after:

enter image description here

what I want:

enter image description here


Solution

  • When you create your new UIImage instance, don't forget to use the scale and orientaion values from the original UIImage.

    return UIImage(
      cgImage: cgimg, 
      scale: image.scale, 
      orientation: image.imageOrientation)