views:

226

answers:

1

Hi All,

I am writing an iPhone app that uses AVFoundation for the camera stuff and I'm trying to save the UIImage from the camera into the Camera Roll.

It currently does it this way...

[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];
  }
 }];

I have been watching the WWDC tutorial videos and I think that the 2 lines (NSData... and UIImage...) are a long way round of getting from imageDataSampleBuffer to a UIImage.

It seems to take far too long to save the images to the library.

Does anyone know if there is a single line transition to get the UIImage out of this?

Thanks for any help!

Oliver

A: 

I think doing this in the completion handler block might be more efficient, but you're right, it's saving to the library that takes the biggest chunk of time.

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);
smallduck