使用IOS中的AVFoundation捕获相机图像以及实时滤镜

时间:2018-08-09 05:24:56

标签: ios avfoundation swift4

我正在制作Live Sticker应用并使用AVFoundation捕获图像。 我遇到的问题是,当我保存图像时,它仅保存图像,而不保存放置在图像上的贴纸 我有两个问题
1 =>使用实时贴纸保存图像 2 =>将图像方向更改为纵向模式

相机预览层代码I am getting just image not live sticker

I want to save image with sticker like shown in image but getting only image

     func setupCameraPreview() {
    self.previewLayer = AVCaptureVideoPreviewLayer(session: self.session)
    self.previewLayer.videoGravity = AVLayerVideoGravity.resizeAspect
    let rootLayer = self.overlay.layer

    rootLayer.masksToBounds = true
    self.previewLayer.frame = rootLayer.bounds
    rootLayer.addSublayer(self.previewLayer)
}

我正在使用此代码保存图像

    private func imageFromSampleBuffer(sampleBuffer: CMSampleBuffer) -> UIImage? {
    guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
    let ciImage = CIImage(cvPixelBuffer: imageBuffer)
    let context = CIContext()
    guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return nil }
    return UIImage(cgImage: cgImage)
}

1 个答案:

答案 0 :(得分:0)

您必须与覆盖贴纸一起绘制图像。

假设您在preview视图中添加了标签。
image是您从imageFromSampleBufferstillImage

获得的图片
var imageView = UIImageView(image: image)
imageView.frame = preview.bounds
//   imageView.contentMode = UIViewContentModeScaleAspectFit;
preview.addSubview(imageView)
preview.sendSubview(toBack: imageView)
var layer: CALayer? = preview.layer
UIGraphicsBeginImageContextWithOptions((layer?.frame.size)!, false, 0.0)
if let aContext = UIGraphicsGetCurrentContext() {
    layer?.render(in: aContext)
}
var img: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

 self.yourImageView.image = img