-
-
Save trilliwon/7abed0f34c66f01f60a6a61ed00b9d5b to your computer and use it in GitHub Desktop.
AVFoundation Camera ScreenShot snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)setupCaptureSession | |
{ | |
NSError *error = nil; | |
AVCaptureSession *session = [[AVCaptureSession alloc] init]; | |
session.sessionPreset = AVCaptureSessionPresetMedium; | |
AVCaptureDevice *device = [AVCaptureDevice | |
defaultDeviceWithMediaType:AVMediaTypeVideo]; | |
AVCaptureDeviceInput *input = [AVCaptureDeviceInput | |
deviceInputWithDevice:device | |
error:&error]; | |
if (!input) { | |
// Handling the error appropriately | |
} | |
[session addInput:input]; | |
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] | |
init]; | |
[session addOutput:output]; | |
dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL); | |
[output setSampleBufferDelegate:self queue:queue]; | |
dispatch_release(queue); | |
output.videoSettings = | |
[NSDictionary dictionaryWithObject: | |
[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] | |
forKey:(id)kCVPixelBufferPixelFormatTypeKey]; | |
output.minFrameDuration = CMTimeMake(1, 15); | |
[session startRunning]; | |
[self setSession:session]; | |
} | |
- (void)captureOutput:(AVCaptureOutput *)captureOutput | |
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer | |
fromConnection:(AVCaptureConnection *)connection | |
{ | |
UIImage *image = [self imageFromSampleBuffer:sampleBuffer]; | |
< Add your code here that uses the image > | |
} | |
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sample | |
{ | |
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sample); | |
CVPixelBufferLockBaseAddress(imageBuffer, 0); | |
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer); | |
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); | |
size_t width = CVPixelBufferGetWidth(imageBuffer); | |
size_t height = CVPixelBufferGetHeight(imageBuffer); | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); | |
CGContextRef context = CGBitmapContextCreate(baseAddress, width, | |
height, 8, | |
bytesPerRow, colorSpace, | |
kCGBitmapByteOrder32Little | | |
kCGImageAlphaPremultipliedFirst); | |
CGImageRef quartzImage = CGBitmapContextCreateImage(context); | |
CVPixelBufferUnlockBaseAddress(imageBuffer,0); | |
CGContextRelease(context); | |
CGColorSpaceRelease(colorSpace); | |
UIImage *image = [UIImage imageWithCGImage:quartzImage]; | |
CGImageRelease(quartzImage); | |
return (image); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment