Estoy tratando de capturar video desde una cámara. He recibido la devolución de llamada captureOutput:didOutputSampleBuffer:
para activar y me da un buffer de muestra que luego convierto a CVImageBufferRef
. Luego intento convertir esa imagen a UIImage
que luego puedo ver en mi aplicación.cómo convertir un CVImageBufferRef a UIImage
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
/*Lock the image buffer*/
CVPixelBufferLockBaseAddress(imageBuffer,0);
/*Get information about the image*/
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
/*We unlock the image buffer*/
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
/*Create a CGImageRef from the CVImageBufferRef*/
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGImageRef newImage = CGBitmapContextCreateImage(newContext);
/*We release some components*/
CGContextRelease(newContext);
CGColorSpaceRelease(colorSpace);
/*We display the result on the custom layer*/
/*self.customLayer.contents = (id) newImage;*/
/*We display the result on the image view (We need to change the orientation of the image so that the video is displayed correctly)*/
UIImage *image= [UIImage imageWithCGImage:newImage scale:1.0 orientation:UIImageOrientationRight];
self.capturedView.image = image;
/*We relase the CGImageRef*/
CGImageRelease(newImage);
}
el código parece funcionar bien hasta la llamada a CGBitmapContextCreate
. siempre devuelve un puntero NULL
. por lo tanto, ninguno de los demás funciona. pase lo que pase, la función devuelve null. no tengo ni idea de porqué.
completamente la respuesta correcta, por lo que sólo como un comentario: kCVPixelFormatType_32RGBA no está disponible como un formato de captura en el iPhone 4 al menos en iOS 4.2.1 . BGRA está completamente implementado. – Tommy