Monday, November 24, 2014

CIFilter - Invert the photo color by built-in filter

//Updated December 22, 2014:
//Keep the photo orientation.

//Updated December 30, 2014
//Remove the error: BSXPCMessage received error for message: Connection interrupted
//Modify this: CIContext(options:[kCIContextUseSoftwareRenderer: true])


import UIKit

class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var picture: UIImageView!
    
    @IBAction func photoAlbum(sender: AnyObject) {
        if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) {
            var pickerController = UIImagePickerController()
            pickerController.delegate = self
            self.presentViewController(pickerController, animated: true, completion: nil)
        }
    }
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        
        let uiPictureSelected = info[UIImagePickerControllerOriginalImage] as UIImage
        let myOrientation : UIImageOrientation = uiPictureSelected.imageOrientation //Keep the photo orientation.
        let ciPictureSelected = CIImage(image:uiPictureSelected)

        var myFilter = CIFilter(name: "CIColorInvert")
        myFilter.setValue(ciPictureSelected, forKey: kCIInputImageKey)
        
        let ciOutputImage = myFilter.outputImage
        
        let ciContext = CIContext(options:[kCIContextUseSoftwareRenderer: true])
        let cgOutputImage = ciContext.createCGImage(ciOutputImage, fromRect: ciOutputImage.extent())
        
        let uiOutputImage = UIImage(CGImage: cgOutputImage, scale: 1, orientation: myOrientation)
        self.picture.image = uiOutputImage
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

No comments:

Post a Comment