IOS uses AVCaptureSession to customize the camera,

Source: Internet
Author: User

IOS uses AVCaptureSession to customize the camera,

For iOS, when we call a camera to obtain photos, we usually call UIImagePickerController to call the camera provided by the system to take photos. This control is very useful. However, sometimes the UIImagePickerController control cannot meet our needs. For example, if we need a more complex OverlayerView, we need to construct a camera control by ourselves.

This requires the components in the framework AVFoundation. framework. Therefore, we need to first import the header file <AVFoundation/AVFoundation. h>. In addition, the official component documentation is also required:

● An instance of AVCaptureDevice to represent the input device, such as a camera or microphone
● An instance of a concrete subclass of AVCaptureInput to configure the ports from the input device
● An instance of a concrete subclass of AVCaptureOutput to manage the output to a movie file or still image
● An instance of AVCaptureSession to coordinate the data flow from the input to the output


Here I only constructed a camera with the camera function. The video and recording functions are not described here.

To sum up, we need the following objects:

@ Property (nonatomic, strong) AVCaptureSession * session; // AVCaptureSession object for data transmission between the input device and the output device @ property (nonatomic, strong) AVCaptureDeviceInput * videoInput; // The AVCaptureDeviceInput object is the input stream @ property (nonatomic, strong) AVCaptureStillImageOutput * stillImageOutput; // The photo output stream object. Of course, my camera only has the photo function, therefore, only this object is enough. @ property (nonatomic, strong) AVCaptureVideoPreviewLayer * previewLayer; // preview layer to display the image taken by the camera @ property (nonatomic, strong) UIBarButtonItem * toggleButton; // the button for switching between front and rear lenses @ property (nonatomic, strong) UIButton * shutterButton; // The photo button @ property (nonatomic, strong) UIView * cameraShowView; // place the View of the preview Layer

I used to create these objects when executing the init method, and then load the preview LAYER IN THE viewWillAppear method. Now let's take a look at the code.

-(Void) initialSession {// the execution of this method is put in the init method self. session = [[AVCaptureSession alloc] init]; self. videoInput = [[AVCaptureDeviceInput alloc] initWithDevice: [self frontCamera] error: nil]; // The [self fronCamera] method returns an AVCaptureDevice object because I used the front camera during initialization, therefore, the specific implementation method will introduce self later. stillImageOutput = [[AVCaptureStillImageOutput alloc] init]; NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil]; // This is the Setting Parameter of the output stream. AVVideoCodecJPEG indicates that the image is output in JPEG format [self. stillImageOutput setOutputSettings: outputSettings]; if ([self. session canAddInput: self. videoInput]) {[self. session addInput: self. videoInput];} if ([self. session canAddOutput: self. stillImageOutput]) {[self. session addOutput: self. stillImageOutput] ;}}
This is how to get the front and back camera objects

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition) position {NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];for (AVCaptureDevice *device in devices) {if ([device position] == position) {return device;}}return nil;}- (AVCaptureDevice *)frontCamera {return [self cameraWithPosition:AVCaptureDevicePositionFront];}- (AVCaptureDevice *)backCamera {return [self cameraWithPosition:AVCaptureDevicePositionBack];}

Next, load the preview layer in the viewWillAppear method.

- (void) setUpCameraLayer{    if (_cameraAvaible == NO) return;        if (self.previewLayer == nil) {        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];        UIView * view = self.cameraShowView;        CALayer * viewLayer = [view layer];        [viewLayer setMasksToBounds:YES];                CGRect bounds = [view bounds];        [self.previewLayer setFrame:bounds];        [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];                [viewLayer insertSublayer:self.previewLayer below:[[viewLayer sublayers] objectAtIndex:0]];            }}

Note the following methods to enable and disable session in viewDidAppear and viewDidDisappear

- (void) viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    if (self.session) {        [self.session startRunning];    }}- (void) viewDidDisappear:(BOOL)animated{    [super viewDidDisappear: animated];    if (self.session) {        [self.session stopRunning];    }}

Next, we will implement the button for switching between the front and back lenses. I will not say much about the creation of the button.

- (void)toggleCamera {    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];if (cameraCount > 1) {        NSError *error;        AVCaptureDeviceInput *newVideoInput;        AVCaptureDevicePosition position = [[_videoInput device] position];                if (position == AVCaptureDevicePositionBack)            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:&error];        else if (position == AVCaptureDevicePositionFront)            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:&error];        else            return;                if (newVideoInput != nil) {            [self.session beginConfiguration];            [self.session removeInput:self.videoInput];            if ([self.session canAddInput:newVideoInput]) {                [self.session addInput:newVideoInput];                [self setVideoInput:newVideoInput];            } else {                [self.session addInput:self.videoInput];            }            [self.session commitConfiguration];        } else if (error) {NSLog(@"toggle carema failed, error = %@", error);        }    }}

This is the method to switch the lens button.

- (void) shutterCamera{    AVCaptureConnection * videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];    if (!videoConnection) {        NSLog(@"take photo failed!");        return;    }        [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {        if (imageDataSampleBuffer == NULL) {            return;        }        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];        UIImage * image = [UIImage imageWithData:imageData];        NSLog(@"image size = %@",NSStringFromCGSize(image.size));    }];}
This is the photo button method.

In this way, the simple functions of the custom camera are completed. If you want to add other complex functions, refer to the Article below in the workshop. I hope it will be helpful to you.

Http://course.gdou.com/blog/Blog.pzs/archive/2011/12/14/10882.html




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.