2016-03-01 27 views
0

這是一個相當流行的問題,但我還沒有找到解決我的問題。 我從iPhone的前置攝像頭,這樣從CMSampleBufferr製作UIImage會發生什麼?

func captureOutput(captureOutput: AVCaptureOutput, didOutputSampleBuffer sampleBuffer: CMSampleBufferRef, fromConnection connection: AVCaptureConnection) { 
    let uiImage = imageFromSampleBufferDep(sampleBuffer) 
    ... 
    UIImageWriteToSavedPhotosAlbum(uiImage!, self, "image:didFinishSavingWithError:contextInfo:", nil) 
    ... 
} 

func imageFromSampleBufferDep(sampleBuffer: CMSampleBuffer) -> UIImage? { 
    let imageBuffer: CVImageBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)! 
    CVPixelBufferLockBaseAddress(imageBuffer, 0) 
    let address = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0) 
    let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer) //1924 
    let width = CVPixelBufferGetWidth(imageBuffer) //1280 
    let height = CVPixelBufferGetHeight(imageBuffer) //720 

    let colorSpace = CGColorSpaceCreateDeviceRGB() 

    let context = CGBitmapContextCreate(address, width, height, 8, bytesPerRow, colorSpace, CGImageAlphaInfo.NoneSkipFirst.rawValue) 
    let imageRef = CGBitmapContextCreateImage(context) 

    CVPixelBufferUnlockBaseAddress(imageBuffer, 0) 
    var resultImage : UIImage? 
    if context != nil { 
     resultImage = UIImage(CGImage: imageRef!) 
    } 

    return resultImage 
} 

拍攝框架和我有一個錯誤:

<Error>: CGBitmapContextCreate: invalid data bytes/row: should be at least 5120 for 8 integer bits/component, 3 components, kCGImageAlphaNoneSkipFirst. 

我試圖直接分配bytesPerRow到5120,但在這種情況下,我有一組灰色和倒置的圖片(附)

熱點解決這個問題?

enter image description here

+0

你是假設你所得到的像素緩衝區是單平面,是在RGB色彩空間。相機的內容不會是這種格式。首先,您需要使用以下代碼獲取像素格式類型:CVPixelBufferGetPixelFormatType。你也可以看看使用CVPixelBufferGetPlaneCount來找出飛機的數量。爲了得到更好的顏色匹配,你也應該考慮使用'CGColorSpaceRef colorSpace; colorSpace =(CGColorSpaceRef)CVBufferGetAttachment(pixBuffer, kCVImageBufferCGColorSpaceKey,NULL);' – SheffieldKevin

+0

可以給我另一個提示嗎?我做了這些事情。 'var pixelBuffer:CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!; var planesNum = CVPixelBufferGetPlaneCount(pixelBuffer);讓colorSpace = CVBufferGetAttachment(pixelBuffer,kCVImageBufferCGColorSpaceKey,nil)as! CGColorSpaceRef'在這種情況下,colorSpace返回nil。我是對的,那麼我必須交換imageBuffer到pixelBuffer? – albertpod

+0

飛機數量的目的是什麼?必須在哪裏使用? – albertpod

回答

0

其實我做這導致了上述錯誤的傻事。

繼此convert CMSampleBufferRef to UIImage問題。

我這樣做:

var videoCaptureOutput = AVCaptureVideoDataOutput() 

videoCaptureOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey:Int(kCVPixelFormatType_32BGRA)]