使UIImage脱离captureStillImageAsynchronouslyFromConnection

时间:2010-09-05 00:08:10

标签: iphone avcapturesession

我正在编写一个使用AVFoundation进行相机操作的iPhone应用程序,我正试图将UIImage从相机保存到相机胶卷中。

目前这样做......

[imageCaptureOutput captureStillImageAsynchronouslyFromConnection:[imageCaptureOutput.connections objectAtIndex:0]
             completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
 {
  if (imageDataSampleBuffer != NULL)
  {
   NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
   UIImage *image = [[UIImage alloc] initWithData:imageData];

   MyCameraAppDelegate *delegate = [[UIApplication sharedApplication] delegate];

   [delegate processImage:image];
  }
 }];

我一直在观看WWDC教程视频,我认为2行(NSData ...和UIImage ...)是从imageDataSampleBuffer到UIImage的很长一段路。

将图像保存到库中似乎需要太长时间。

有没有人知道是否有单行过渡来使UIImage脱离这个?

感谢您的帮助!

奥利弗

1 个答案:

答案 0 :(得分:3)

我认为在完成处理程序块中执行此操作可能会更有效,但是你是对的,它可以节省占用最大块时间的库。

CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(imageDataSampleBuffer);

CVPixelBufferLockBaseAddress(imageBuffer, 0); 
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); 
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); 
size_t width = CVPixelBufferGetWidth(imageBuffer); 
size_t height = CVPixelBufferGetHeight(imageBuffer); 
CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); 
CGImageRef cgImage = CGBitmapContextCreateImage(context); 
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);

if ( /*wanna save metadata on iOS4.1*/ ) {
  CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL, imageDataSampleBuffer, kCMAttachmentMode_ShouldPropagate);
  [assetsLibraryInstance writeImageToSavedPhotosAlbum:cgImage metadata:metadataDict completionBlock:^(NSURL *assetURL, NSError *error) { /*do something*/ }];
  CFRelease(metadataDict);
} else {
  [assetsLibraryInstance writeImageToSavedPhotosAlbum:cgImage orientation:ALAssetOrientationRight completionBlock:^(NSURL *assetURL, NSError *error) { /*do something*/ }];
  // i think this is the correct orientation for Portrait, or Up if deviceOr'n is L'Left, Down if L'Right
}
CGImageRelease(cgImage);