AVCapture-Camera

2018-05-18  本文已影响19人  ElaineYin

对AVCapture不太理解的童鞋请看上一篇:AVCapture详解

需要Camera Demo的童鞋可以直接下载

下面就做个自定义相机的练习

tips:练习用的output是AVCaptureStillImageOutput,iOS10之后用 AVCapturePhotoOutput,请童鞋们注意适配

  1. 首先定义一下Camera需要用到的AVCapture对象
//session
AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];
//设置session采集质量 
captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
//摄像头
AVCaptureDevice  *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//输入流
NSError *error;
AVCaptureDeviceInput  *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
//输出流
AVCaptureStillImageOutput  *imageOutput = [[AVCaptureStillImageOutput alloc] init];
// 这是输出流的设置参数AVVideoCodecJPEG参数表示以JPEG的图片格式输出图片
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
[imageOutput setOutputSettings:outputSettings];
  1. 给session添加input、output
- (void)sessionConfig {
    [self.captureSession beginConfiguration];
    if ([self.captureSession canAddInput:self.captureInput]) {
        [self.captureSession addInput:self.captureInput];
    }
    if ([self.captureSession canAddOutput:self.imageOutput]) {
        [self.captureSession addOutput:self.imageOutput];
    }
    [self.captureSession commitConfiguration];
}
  1. 添加摄像头预览
AVCaptureVideoPreviewLayer *preLayer = [AVCaptureVideoPreviewLayer layerWithSession: captureSession];
preLayer.frame = self.view.bounds;
preLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:preLayer];
  1. 启动session
//启动
[self.captureSession startRunning];
  1. 拍照
    利用AVCaptureStillImageOutput和AVCaptureConnection获取CMSampleBufferRef,再转换成UIImage
AVCaptureConnection *conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
[self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
    if (error || imageDataSampleBuffer == nil) {
         return;
     }
     NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
     UIImage *image = [UIImage imageWithData:imageData];
 }];
上一篇下一篇

猜你喜欢

热点阅读