Mr. A Mr. A - 1 year ago 135
Swift Question

UIImagePNG representation from AVFoundation returns nil

I have a capture output delegate method:

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
let filter = CIFilter(name: "CIColorControls")
let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let cameraImage = CIImage(cvPixelBuffer: pixelBuffer!)

filter?.setValue(cameraImage, forKey: kCIInputImageKey)
filter?.setValue(0.0, forKey: kCIInputSaturationKey)

let filteredImage = UIImage(ciImage: filter!.value(forKey: kCIOutputImageKey) as! CIImage!, scale: 1.0, orientation: UIImageOrientation.right)

DispatchQueue.main.async {
self.cameraView.image = filteredImage


where I add filter to my live preview image. But if i try to create NSData from the image by this method: UIImagePNGRepresentation() it's return nil and I have don't idea why. If I use CameraViewController all works perfect so I think that the problem is in AVFoundation. Any tips?

Answer Source

The problem is that UIImage(ciImage:) does not convert a CIImage to a normal UIImage. You need to render into a normal UIImage backed by a CGImage.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download