首页 > 代码库 > 多媒体编程——ios摄像头图像抓取工具类

多媒体编程——ios摄像头图像抓取工具类

工具类提供预览图像画面,自动处理旋转,并且以主动方式抓取图像(这样帧率可以无限大)

系统的接口多是异步接收图像,像我这种强迫症怎么受得了,必须吧被动接收图像的方式改成主动抓取。


头文件


#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>

//这些比例都是4:3的比例。
typedef enum TKVideoFrameSize
{
    tkVideoFrame480x360     = 480  << 16 | 360,
    tkVideoFrame720x540     = 720  << 16 | 540, //用这个分辨率,效率会快很多。
}TKVideoFrameSize;



@interface TKVideoCapture : NSObject <AVCaptureVideoDataOutputSampleBufferDelegate>

- (bool) create:(UIView*)preview frame:(TKVideoFrameSize)type ;
- (bool) destory;

- (bool) start ;
- (bool) stop ;

//返回 字节顺序 BGRA BGRA 的图像数据。
- (uint8_t*) get_image_rgb32:(uint32_t*)length ;

@end




实现文件:(里面用到了那个Lock可以去上一篇文章找)


#import "TKVideoCapture.h"
#import <UIKit/UIKit.h>
#import <CoreGraphics/CoreGraphics.h>
#import <CoreVideo/CoreVideo.h>
#import <CoreMedia/CoreMedia.h>
#import "TKLock.h"

@interface TKVideoCapture ()
{
    TKVideoFrameSize            _frametype      ;
    UIView*                     _preview        ;
    AVCaptureSession*           _captureSession ;
    AVCaptureVideoPreviewLayer* _capturePreview ;
    AVCaptureVideoDataOutput *  _captureOutput  ;
    AVCaptureDevice*            _captureDevice  ;
    AVCaptureDeviceInput*       _captureInput   ;
    
    uint8_t*                    _buffer_temp    ; //每一帧数据都存储到这个缓存中
    uint8_t*                    _buffer_obox    ; //需要使用时,从tempbuf 拷贝过来。
    CGRect                      _subImageRect   ; //子图片的位置。
    
    TKLock*                     _buffer_lock    ;
}

@end


@implementation TKVideoCapture

- (void) do_create
{
    self->_captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo] ;
    self->_captureInput  = [AVCaptureDeviceInput deviceInputWithDevice:self->_captureDevice  error:nil];
    self->_captureOutput = [[AVCaptureVideoDataOutput alloc] init];
    
    if(self->_captureOutput)
        [self->_captureOutput setAlwaysDiscardsLateVideoFrames:true];
    
    dispatch_queue_t queue = dispatch_queue_create("cameraQueue", NULL);
    [self->_captureOutput setSampleBufferDelegate:self queue:queue];
    
    dispatch_release(queue);
    
    
    NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
    NSNumber* value = http://www.mamicode.com/[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];>