AVCaptureStillImageOutput

AVCaptureStillImageOutput

我第一次使用AVCaptureStillImageOutput,有时会保存JPEG图像。
我想保存一个PNG图像,而不是JPEG图像。我该怎么办?

我在应用程序中有这三行代码:

let stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)

有没有简单的方法可以修改这些行以获得我想要的?
浏览完网络之后,似乎分析者没有(除非我还不够幸运),但是我仍然相信必须有一些好的解决方案。

最佳答案

AVFoundation Programming Guide中包含示例代码,该示例代码显示如何将CMSampleBuffer转换为UIImage(在将CMSampleBuffer转换为UIImage对象下)。从那里,您可以使用UIImagePNGRepresentation(image)将其编码为PNG数据。

这是该代码的Swift翻译:

extension UIImage
{
    // Translated from <https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/06_MediaRepresentations.html#//apple_ref/doc/uid/TP40010188-CH2-SW4>
    convenience init?(fromSampleBuffer sampleBuffer: CMSampleBuffer)
    {
        guard let imageBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }

        if CVPixelBufferLockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess { return nil }
        defer { CVPixelBufferUnlockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly) }

        let context = CGBitmapContextCreate(
            CVPixelBufferGetBaseAddress(imageBuffer),
            CVPixelBufferGetWidth(imageBuffer),
            CVPixelBufferGetHeight(imageBuffer),
            8,
            CVPixelBufferGetBytesPerRow(imageBuffer),
            CGColorSpaceCreateDeviceRGB(),
            CGBitmapInfo.ByteOrder32Little.rawValue | CGImageAlphaInfo.PremultipliedFirst.rawValue)

        guard let quartzImage = CGBitmapContextCreateImage(context) else { return nil }
        self.init(CGImage: quartzImage)
    }
}

关于ios - AVCaptureStillImageOutput.pngStillImageNSDataRepresentation?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34605236/

10-10 20:50