使用Swift上的GPUImage过滤器捕获图像

时间:2017-06-10 13:01:36

标签: ios swift gpuimage image-capture

我正在使用GPUImage Framework for Image过滤器。

我在相机上应用了ToonFilter()以实现卡通滤镜效果。

我的问题是在使用GPUImage的ToonFilter效果在相机上捕获图像时。

以下是使用GPUImage相机显示ToonFilter的代码。捕获具有相同效果的新图像。

请指导我如何使用相同的过滤器捕获图像?

注意:我已成功打开具有ToonFilter效果的相机 - 问题只是捕获带有滤镜效果的新图像。

代码:

import UIKit
import GPUImage
import AVFoundation

class SelfieFilterVC: UIViewController, UISplitViewControllerDelegate  {

    @IBOutlet var filterSlider: UISlider?
    @IBOutlet var filterView: RenderView?

    let videoCamera:Camera?
    var blendImage:PictureInput?

    override func viewDidLoad() {

        super.viewDidLoad()

        self.filterOperation = FilterOperation(
            filter:{ToonFilter()},
            listName:"Toon",
            titleName:"Toon",
            sliderConfiguration:.disabled,
            sliderUpdateCallback: nil,
            filterOperationType:.singleInput
        )

        self.configureView()
    }

    required init(coder aDecoder: NSCoder)
    {
        do {
            videoCamera = try Camera(sessionPreset:AVCaptureSessionPreset640x480, location:.backFacing)
            videoCamera!.runBenchmark = true

        } catch {
            videoCamera = nil
            print("Couldn't initialize camera with error: \(error)")
        }

        super.init(coder: aDecoder)!
    }

    var filterOperation: FilterOperationInterface?


    @IBAction func btnCapture(_ sender: Any) {

        videoCamera?.startCapture()

        let pictureOutput = PictureOutput()
        pictureOutput.encodedImageFormat = .jpeg
        pictureOutput.encodedImageAvailableCallback = {imageData in

            if imageData != nil {
                let captureDetailVC = self.storyboard?.instantiateViewController(withIdentifier: "CaptureDetailVC") as! CaptureDetailVC
                captureDetailVC.aCaptureSelectedData = imageData
                self.show(captureDetailVC, sender: true)
            }
        }
    }

    @IBAction func btnBackAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    func configureView() {

        guard let videoCamera = videoCamera else {

            let errorAlertController = UIAlertController(title: NSLocalizedString("Error", comment: "Error"), message: "Couldn't initialize camera", preferredStyle: .alert)
            errorAlertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: .default, handler: nil))
            self.present(errorAlertController, animated: true, completion: nil)
            return
        }

        if let currentFilterConfiguration = self.filterOperation {
            self.title = currentFilterConfiguration.titleName

            // Configure the filter chain, ending with the view
            if let view = self.filterView {
                switch currentFilterConfiguration.filterOperationType {
                case .singleInput:
                    videoCamera.addTarget(currentFilterConfiguration.filter)
                    currentFilterConfiguration.filter.addTarget(view)
                case .blend:
                    videoCamera.addTarget(currentFilterConfiguration.filter)
                    self.blendImage = PictureInput(imageName:blendImageName)
                    self.blendImage?.addTarget(currentFilterConfiguration.filter)
                    self.blendImage?.processImage()
                    currentFilterConfiguration.filter.addTarget(view)
                case let .custom(filterSetupFunction:setupFunction):
                    currentFilterConfiguration.configureCustomFilter(setupFunction(videoCamera, currentFilterConfiguration.filter, view))
                }

                videoCamera.startCapture()
            }

            // Hide or display the slider, based on whether the filter needs it
            if let slider = self.filterSlider {
                switch currentFilterConfiguration.sliderConfiguration {
                case .disabled:
                    slider.isHidden = true
                //                case let .Enabled(minimumValue, initialValue, maximumValue, filterSliderCallback):
                case let .enabled(minimumValue, maximumValue, initialValue):
                    slider.minimumValue = minimumValue
                    slider.maximumValue = maximumValue
                    slider.value = initialValue
                    slider.isHidden = false
                    self.updateSliderValue()
                }
            }

        }
    }

    @IBAction func updateSliderValue() {
        if let currentFilterConfiguration = self.filterOperation {
            switch (currentFilterConfiguration.sliderConfiguration) {
            case .enabled(_, _, _): currentFilterConfiguration.updateBasedOnSliderValue(Float(self.filterSlider!.value))
            case .disabled: break
            }
        }
    }



    override func viewWillDisappear(_ animated: Bool) {
        if let videoCamera = videoCamera {
            videoCamera.stopCapture()
            videoCamera.removeAllTargets()
            blendImage?.removeAllTargets()
        }

        super.viewWillDisappear(animated)
    }
}

1 个答案:

答案 0 :(得分:0)

使用GPUImage捕获图像的方法是使用方法imageFromCurrentFramebuffer,您可以使用该方法来过滤。

它返回UIImage,您可以稍后将其转换为您需要的任何图像格式并保存。

let image:UIImage = filter.imageFromCurrentFramebuffer()
if let data = UIImageJPEGRepresentation(image, 0.8) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let filename = documentsDirectory.appendingPathComponent("image.jpg")
    try? data.write(to: filename)
}