AVFoundation-自定义拍照

AVCaptureSession是AVFoundation的核心类,用于捕捉视频和音频,协调视频和音频的输入和输出流.

  • 输入源
    设备AVCaptureDevice
    [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]
  • 输出源
    添加AVCaptureOutput,即AVCaptureSession的输出源.一般输出源分成:音视频源,图片源,文件源等.
    音视频输出AVCaptureAudioDataOutput,AVCaptureVideoDataOutput.
    静态图片输出AVCaptureStillImageOutput(iOS10中被AVCapturePhotoOutput取代了)
    AVCaptureMovieFileOutput表示文件源.

创建会话AVCaptureSession

-(AVCaptureSession *)captureSession{
    if (!_captureSession) {
        _captureSession = [[AVCaptureSession alloc]init];
        if ([[UIDevice currentDevice]userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            customLog(@"当前使用的是手机");
        }
    }
    return _captureSession;
}

创建输入源

1、创建AVCaptureDevice

-(AVCaptureDevice *)getCaptureDevice{
    // 每次获取都要重新创建
    NSArray * devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice * device in devices) {
        if (device.position == self.captureDevicePosition) {
            NSError * error = nil;
            if ([device lockForConfiguration:&error]) {
                // 焦点 曝光 黑白色 -> 自动
                if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
                    device.focusMode = AVCaptureFocusModeContinuousAutoFocus;
                }
                if ([device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
                    device.exposureMode = AVCaptureExposureModeContinuousAutoExposure;
                }
                if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
                    device.whiteBalanceMode = AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance;
                }
                
                [device unlockForConfiguration];
            }
            
            _captureDevice = device;
            return _captureDevice;
        }
    }
    return nil;
}

2、创建AVCaptureDeviceInput

-(AVCaptureDeviceInput *)getCaptureDeviceInput{
    NSError * error = nil;
    AVCaptureDevice * device = [self getCaptureDevice];
    _captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (error || device == nil) {
        NSLog(@"创建失败: %@",error.description);
    }
    return _captureDeviceInput;
}

3、添加输入源到会话中

AVCaptureSession * session = self.captureSession;
    // 添加输入对象到会话
    if ([session.inputs containsObject:self.captureDeviceInput]) {
        [session removeInput:self.captureDeviceInput];
    }
    AVCaptureDeviceInput * input = [self getCaptureDeviceInput];
    if ([session canAddInput:input]) {
        [session addInput:input];
    }

创建输出源并添加到会话中

 // 添加照片输出
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
        AVCapturePhotoOutput * photoOutput = [[AVCapturePhotoOutput alloc]init];
        
        // 先移除
        if ([session.outputs containsObject:self.captureOutput]) {
            [session removeOutput:self.captureOutput];
        }
        // 添加
        if ([session canAddOutput:photoOutput]) {
            [session addOutput:photoOutput];
        }
        
        self.captureOutput = photoOutput;
    }else{
        AVCaptureStillImageOutput * stillImageOutput = [[AVCaptureStillImageOutput alloc]init];
        NSDictionary *myOutputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
        [stillImageOutput setOutputSettings:myOutputSettings];
        
        // 先移除
        if ([session.outputs containsObject:self.captureOutput]) {
            [session removeOutput:self.captureOutput];
        }
        // 添加
        if ([session canAddOutput:stillImageOutput]){
            [session addOutput:stillImageOutput];
        }
        
        self.captureOutput = stillImageOutput;
    }   

输出对象-视频流对象作为输出适合及时获取输出数据(直播)

    AVCaptureVideoDataOutput *videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
    [videoDataOutput setAlwaysDiscardsLateVideoFrames:YES];// 默认为YES
    // 设置代理,捕获视频样品数据
    // 注意:队列必须是串行队列,才能获取到数据,而且不能为空
    dispatch_queue_t photoCaptureQueue = dispatch_queue_create(MDPhotoCaptureQueue, DISPATCH_QUEUE_SERIAL);
    [videoDataOutput setSampleBufferDelegate:self queue:photoCaptureQueue];
    if ([session canAddOutput:videoDataOutput]) {
        [session addOutput:videoDataOutput];
    }
    #pragma mark AVCaptureVideoDataOutputSampleBufferDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
- // 及时获取视频输出数据
    customLog(@"采集到数据");
}

添加预览图层

-(void)addPreviewLayer{
    // 视频预览图层
    AVCaptureVideoPreviewLayer *previedLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    previedLayer.frame = [UIScreen mainScreen].bounds;
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer insertSublayer:previedLayer atIndex:0];
    _previewLayer = previedLayer;
}

切换前后置摄像头-切换输入源

- (void)changeInput{
    // 移除输入对象
    if (self.captureDeviceInput && [self.captureSession.inputs containsObject:self.captureDeviceInput]) {
        [self.captureSession removeInput:self.captureDeviceInput];
    }
    // 添加输入对象到会话
    AVCaptureDeviceInput * input = [self getCaptureDeviceInput];
    if ([self.captureSession canAddInput:input]) {
        [self.captureSession addInput:input];
    }
    self.isChangeCaptureDevicePostion = NO;
    // 给摄像头的切换添加翻转动画
    CATransition *animation = [CATransition animation];
    animation.duration = .5f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.type = @"oglFlip";
    if (self.captureDevicePosition == AVCaptureDevicePositionFront) {
        animation.subtype = kCATransitionFromLeft;
    }else{
        animation.subtype = kCATransitionFromRight;
    }
    [self.previewLayer addAnimation:animation forKey:nil];
}

拍照按钮点击-获取图片

-(void)commitButtonAction{
    // 拍照
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
        
        AVCapturePhotoOutput * output = (AVCapturePhotoOutput *)self.captureOutput;
        
        //从 AVCaptureStillImageOutput 中取得 AVCaptureConnection
        self.captureConnection = [output connectionWithMediaType:AVMediaTypeVideo];
        AVCapturePhotoSettings * settings = [AVCapturePhotoSettings photoSettings];
        
        [output capturePhotoWithSettings:settings delegate:self];
    }else{
        AVCaptureStillImageOutput * stillImageOutput = (AVCaptureStillImageOutput *)self.captureOutput;
        //从 AVCaptureStillImageOutput 中取得 AVCaptureConnection
        self.captureConnection = [stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
        [stillImageOutput captureStillImageAsynchronouslyFromConnection:self.captureConnection completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
            if (imageDataSampleBuffer != nil) {
                NSData * data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                // 取得静态影像 两种获取方式
                //UIImage * image = [[UIImage alloc]initWithData:data];
                
                CFDataRef cfData = CFBridgingRetain(data);
                CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData(cfData);
                CGImageRef cgImage = CGImageCreateWithJPEGDataProvider(dataProvider, nil, YES, kCGRenderingIntentDefault);
                CFBridgingRelease(cfData);
                
                // 裁剪图片
                [self cropWithImage:[UIImage imageWithCGImage:cgImage]];

                // 取得影像数据(需要ImageIO.framework 与 CoreMedia.framework)
                CFDictionaryRef attachments = CMGetAttachment(imageDataSampleBuffer, kCGImagePropertyExifDictionary, NULL);
                customLog(@"影像属性: %@", attachments);
            }
        }];
    }
}

代理获取图片AVCapturePhotoOutput

#pragma mark AVCapturePhotoCaptureDelegate
// IOS - 11
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
    if (error) {
        customLog(@"获取图片错误 --- %@",error.localizedDescription);
    }
    if (photo) {
        if (@available(iOS 11.0, *)) {
            CGImageRef cgImage = [photo CGImageRepresentation];
            UIImage * image = [UIImage imageWithCGImage:cgImage];
            customLog(@"获取图片成功 --- %@",image);
        } else {
            customLog(@"不是走这个代理方法");
        }
    }
}

- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error{
    if (error) {
        customLog(@"获取图片错误 --- %@",error.localizedDescription);
    }
    if (photoSampleBuffer) {
        NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
        UIImage *image = [UIImage imageWithData:data];
        customLog(@"获取图片成功 --- %@",image);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容