ijason03
ijason03

Reputation: 581

Display camera feed in UIView

I'm looking into displaying the front camera video feed into a UIView similar to how FaceTime does it. I know this can easily be done using AVCaptureVideoPreviewLayer. Is there's another way to do this without using AVCaptureVideoPreviewLayer?

This is merely for educational purposes.

UPDATE: I found that this can be accomplished with UIImagePickerController

UIImagePickerController *cameraView = [[UIImagePickerController alloc] init];
cameraView.sourceType = UIImagePickerControllerSourceTypeCamera;
cameraView.showsCameraControls = NO;
[self.view addSubview:cameraView.view];
[cameraView viewWillAppear:YES]; 
[cameraView viewDidAppear:YES];

Upvotes: 0

Views: 650

Answers (1)

Khaled Barazi
Khaled Barazi

Reputation: 8741

If you are trying to manipulate the pixels, you could put the following method in the class you are assigning as delegate to AVCaptureVideoDataOutputSampleBufferDelegate:

-(void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
  CVImageBufferRef pb = CMSampleBufferGetImageBuffer(sampleBuffer);

  if(CVPixelBufferLockBaseAddress(pb, 0))  //zero is success
    NSLog(@"Error");

    size_t bufferHeight = CVPixelBufferGetHeight(pb);
    size_t bufferWidth = CVPixelBufferGetWidth(pb);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(pb);

    unsigned char* rowBase= CVPixelBufferGetBaseAddress(pb);


    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL)
      NSLog(@"Error");

    // Create a bitmap graphics context with the sample buffer data.
    CGContextRef context= CGBitmapContextCreate(rowBase,bufferWidth,bufferHeight, 8,bytesPerRow, colorSpace,  kCGImageAlphaNone);

    // Create a Quartz image from the pixel data in the bitmap graphics context
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);

    UIImage *currentImage=[UIImage imageWithCGImage:quartzImage];

    // Free up the context and color space
    CFRelease(quartzImage);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    if(CVPixelBufferUnlockBaseAddress(pb, 0 )) //zero is success
    NSLog(@"Error");
}

And then hookup that image to an UIImageView in your View controller. Lookinto the kCGImageAlphaNone flag. It will depend what you are doing.

Upvotes: 3

Related Questions