iosswiftuiimagecore-imageuigraphicsimagerenderer

UIGraphicsImageRenderer mirrors image after applying filter


I'm trying to apply filters on images. Applying the filter works great, but it mirrors the image vertically.

The bottom row of images calls the filter function after init.

The main image at the top, gets the filter applied after pressing on one at the bottom

The ciFilter is CIFilter.sepiaTone().

func applyFilter(image: UIImage) -> UIImage? {
        let rect = CGRect(origin: CGPoint.zero, size: image.size)
        let renderer = UIGraphicsImageRenderer(bounds: rect)

        ciFilter.setValue(CIImage(image: image), forKey: kCIInputImageKey)
        
        let image = renderer.image { context in
            let ciContext = CIContext(cgContext: context.cgContext, options: nil)

            if let outputImage = ciFilter.outputImage {
                ciContext.draw(outputImage, in: rect, from: rect)
            }
        }

        return image
    }

And after applying the filter twice, the new image gets zoomed in.

Here are some screenshots. Start After applying the filter After applying the filter the second time


Solution

  • You don't need to use UIGraphicsImageRenderer. You can directly get the image from CIContext.

    func applyFilter(image: UIImage) -> UIImage? {
            
            ciFilter.setValue(CIImage(image: image), forKey: kCIInputImageKey)
            
            guard let ciImage = ciFilter.outputImage else {
                return nil
            }
            let outputCGImage = CIContext().createCGImage(ciImage, from: ciImage.extent)
            
            guard let _ = outputCGImage else { return nil }
            let filteredImage = UIImage(cgImage: outputCGImage!, scale: image.scale, orientation: image.imageOrientation)
            
            return filteredImage
        }