Joe Joe - 6 months ago 116
Swift Question

Reset CoreImage filter in Swift

I am developing simple coreImage filter project in Swift.I am trying to achieve a function like resetting the filtered image back to original. I am using the following code for SepiaTone filter and I am trying to reset the filter using CIColorControls filter.But I am getting fatal crash.I wondering is there any other way to reset the image.

@IBOutlet weak var originalImage: UIImageView!

@IBAction func SepiaToneFilter(sender: AnyObject) {
let mySepiaFilter = CIFilter(name: "CISepiaTone")
mySepiaFilter!.setValue(CIImage(image: originalImage.image!), forKey: kCIInputImageKey)
let myOutputImage : CIImage = mySepiaFilter!.outputImage!
originalImage.image = UIImage(CIImage: myOutputImage)
}

@IBAction func ResetFilter(sender: AnyObject) {

let currentFilter = CIFilter(name: "CIColorControls")
let beginImage = CIImage(image: originalImage.image!)
currentFilter!.setValue(beginImage, forKey: kCIInputImageKey
let output = currentFilter!.outputImage

let cgimg = context.createCGImage(output!, fromRect: output!.extent) **//CreateWrappedSurface() failed for a dataprovider-backed CGImageRef.fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)**

let processedImage = UIImage(CGImage: cgimg)
originalImage.image = processedImage
}


//Pick Image Process

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
originalImage.image = image
self.dismissViewControllerAnimated(true, completion: nil);
}


I am not sure how to run the above function inside my ResetFilter(UIButton).

Thanks in Advance

Answer

Why not just hold a reference to the original image? For example:

    @IBOutlet weak var originalImage: UIImageView!
    var userImage?:UIImage

    @IBAction func SepiaToneFilter(sender: AnyObject) {
        let mySepiaFilter = CIFilter(name: "CISepiaTone")
        if let image = self.userImage {
            mySepiaFilter!.setValue(CIImage(image: image), forKey: kCIInputImageKey)
            let myOutputImage : CIImage = mySepiaFilter!.outputImage!            
            originalImage.image = UIImage(CIImage: myOutputImage)
        }
    }

    @IBAction func ResetFilter(sender: AnyObject) {
        if let image = self.userImage {
            self.originalImage.image = image
        }

    } 


    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
            self.userImage = image
            originalImage.image = image
            self.dismissViewControllerAnimated(true, completion: nil);
    }
Comments