想要将摄像头进行视频录制或者拍照可以用UIImagePickerController,不过UIImagePickerController会弹出一个自己的界面,可是有时候我们不想要弹出的这个界面,那么就可以用另一种方法来获取摄像头得到的数据了。
首先需要引入一个包#import <AVFoundation/AVFoundation.h>,接下来你的类需要实现AVCaptureVideoDataOutputSampleBufferDelegate这个协议,只需要实现协议中的一个方法就可以得到摄像头捕获的数据了
- - (void)captureOutput:(AVCaptureOutput *)captureOutput
- didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
- fromConnection:(AVCaptureConnection *)connection
- {
- // Create a UIImage from the sample buffer data
- UIImage *image = [self imageFromSampleBuffer:sampleBuffer];
- mData = UIImageJPEGRepresentation(image, 0.5);//这里的mData是NSData对象,后面的0.5代表生成的图片质量
- }
下面是imageFromSampleBuffer方法,方法经过一系列转换,将CMSampleBufferRef转为UIImage对象,并返回这个对象:
- // Create a UIImage from sample buffer data
- - (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
- {
- // Get a CMSampleBuffer's Core Video image buffer for the media data
- CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
- // Lock the base address of the pixel buffer
- CVPixelBufferLockBaseAddress(imageBuffer, 0);
- // Get the number of bytes per row for the pixel buffer
- void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
- // Get the number of bytes per row for the pixel buffer
- size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
- // Get the pixel buffer width and height
- size_t width = CVPixelBufferGetWidth(imageBuffer);
- size_t height = CVPixelBufferGetHeight(imageBuffer);
- // Create a device-dependent RGB color space
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
- // Create a bitmap graphics context with the sample buffer data
- CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
- bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
- // Create a Quartz image from the pixel data in the bitmap graphics context
- CGImageRef quartzImage = CGBitmapContextCreateImage(context);
- // Unlock the pixel buffer
- CVPixelBufferUnlockBaseAddress(imageBuffer,0);
- // Free up the context and color space
- CGContextRelease(context);
- CGColorSpaceRelease(colorSpace);
- // Create an image object from the Quartz image
- //UIImage *image = [UIImage imageWithCGImage:quartzImage];
- UIImage *image = [UIImage imageWithCGImage:quartzImage scale:1.0f orientation:UIImageOrientationRight];
- // Release the Quartz image
- CGImageRelease(quartzImage);
- return (image);
- }