简体   繁体   中英

How do I go about applying filters to selected images from the photo library not just hardcoded ones

I'm working on a photo application where the user can select from an image in their photo library or they can take a photo from inside the app using the camera.

I've got the functions working to get the image from either source. I can apply the filters to the image if they are hardcoded with the name of the image, but not when they are selected or taken.

How would I go about changing this so I don't need to hardcode the name of the image into the section for applying the filters to the image?

Here is the code that I have so far on the subject manner.

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var FilterName:String?

    @IBAction func filters(_ sender: UIButton) {
        switch sender.tag {
        case 1: FilterName = "CIGaussianBlur"
        case 2: FilterName = "CIMedianFilter"
        case 3: FilterName = "CIEdges"
        default: print("No Filter Applied")
        }
        process()
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let image = info[.originalImage] as? UIImage
        else
        {
            return
        }
        PhotoView.image = image
        dismiss(animated: true, completion: nil)
    }

    func process() {
        if let image = UIImage("test")
        {
            let originalImage = CIImage(image: image)
            let filter = CIFilter(name: FilterName!)
            filter?.setDefaults()
            filter?.setValue(originalImage, forKey: kCIInputImageKey)
            if let outputImage = filter?.outputImage {
                let newImage = UIImage(ciImage: outputImage)
                PhotoView.image = newImage
            }
        }
    }
}

Since it seems you want to select an image and then have the user tap one of several filter buttons, you need to save the selected image from the image picker to a UIImage property in your class.

Then update your process method to use that property instead of loading a hardcoded image.

Add the following property to your class:

var selectedImage: UIImage? = nil

Then update your image picker delegate method to set this property:

selectedImage = info[.originalImage] as? UIImage

Then update your process method to use the property instead of loading a hardcoded image:

if let image = selectedImage {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM