iOS中的相机取景框架

时间:2015-05-19 01:00:29

标签: ios swift camera

我正在使用SWIFT语言并尝试从相机取景器缓冲区拍摄快照图像。到目前为止,一切都很好,除了图像颜色。它似乎不正确或被交换。下面是我设置视频设置和捕获图像帧的代码片段

func addVideoOutput() {

    videoDeviceOutput = AVCaptureVideoDataOutput()
    videoDeviceOutput.videoSettings = NSDictionary(objectsAndKeys: Int(kCVPixelFormatType_32BGRA), kCVPixelBufferPixelFormatTypeKey) as[NSObject: AnyObject]

    // kCVPixelFormatType_32ARGB tested and found not supported
    videoDeviceOutput.alwaysDiscardsLateVideoFrames = true

    videoDeviceOutput.setSampleBufferDelegate(self, queue: sessionQueue)

    if captureSession!.canAddOutput(videoDeviceOutput) {
        captureSession!.addOutput(videoDeviceOutput)
    }
}

/* AVCaptureVideoDataOutput Delegate
------------------------------------------*/
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
    sessionDelegate ? .cameraSessionDidOutputSampleBuffer ? (sampleBuffer)

    // Extract a UImage
    //var pixel_buffer : CVPixelBufferRef?
    let pixel_buffer = CMSampleBufferGetImageBuffer(sampleBuffer)

    CVPixelBufferLockBaseAddress(pixel_buffer, 0);

    // Get the number of bytes per row for the pixel buffer
    var baseAddress = CVPixelBufferGetBaseAddress(pixel_buffer);

    // Get the number of bytes per row for the pixel buffer
    var bytesPerRow = CVPixelBufferGetBytesPerRow(pixel_buffer);
    // Get the pixel buffer width and height
    let width : Int = CVPixelBufferGetWidth(pixel_buffer);
    let height : Int = CVPixelBufferGetHeight(pixel_buffer);

    /*Create a CGImageRef from the CVImageBufferRef*/
    let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)

    var newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, bitmapInfo)

    CVPixelBufferUnlockBaseAddress(pixel_buffer, 0);

    // get image frame and save to local storage
    var refImage: CGImageRef = CGBitmapContextCreateImage(newContext)
    var pixelData = CGDataProviderCopyData(CGImageGetDataProvider(refImage))

    var image: UIImage = UIImage(CGImage: refImage)!;
    self.SaveImageToDocumentStorage(image)
}

正如你可以看到addVideoOutput函数中的一个注释行,我尝试了kCVPixelFormatType_32ARGB格式,但它说不支持iOS ???

我有点怀疑视频格式是32BGRA,但图像帧的色彩空间是用CGColorSpaceCreateDeviceRGB()设置的,但我找不到任何其他合适的RGB格式用于视频设置。

非常感谢任何解决方案或提示。

由于

1 个答案:

答案 0 :(得分:0)

我找到了原因和解决方案。

以防万一遇到同样的问题。只需更改 bitmapInfo ,如下所示:

// let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)

var bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue) | CGBitmapInfo.ByteOrder32Little