自定义相机 提供两个链接:
http://course.gdou.com/blog/Blog.pzs/archive/2011/12/14/10882.html (原理讲解)
http://www.cnblogs.com/liangzhimy/archive/2012/10/26/2740905.html
保存相片到相册
UIImageWriteToSavedPhotosAlbum(image, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
NSString *alertMessage;
if(!error)
{
alertMessage = @"图片保存成功";
}
else
{
alertMessage = @"图片保存失败";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
message:alertMessage
delegate:self
cancelButtonTitle:@"好"
otherButtonTitles:nil];
[alert show];
}
iOS中使用相机,有两种方式:1:使用ios系统自带的相机。( UIImagePickerController)
2:自定义相机。(利用AVFoundation.framework框架,自定义照相)
第一种:使用iOS系统自带相机。
1:实现 <UINavigationControllerDelegate,UIImagePickerControllerDelegate>这两个协议
2:创建UIImagePickerController实例。(以下是使用相机照相,如果只是想访问系统相册,则可以直接设置代理后,跳转到vc就行,
#pragma mark --从相册中选取图片,然后使用滤镜
- (IBAction)chosePicAndChange:(id)sender
{
if (!self.ipc.delegate) {
self.ipc.delegate=self;
}
[self presentViewController:self.ipc animated:YES completion:nil];
}
)
-(UIImagePickerController *)ipc
{
if (!_ipc) {
_ipc=[UIImagePickerControllernew];
}
return _ipc;
}
//判断是否可以打开相机,模拟器此功能无法使用
if([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
self.ipc.delegate=self;
//是否可编辑
self.ipc.allowsEditing=YES;
//摄像头
self.ipc.sourceType=UIImagePickerControllerSourceTypeCamera;
[selfpresentViewController:self.ipcanimated:YEScompletion:nil];
}else
{
UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"Error"message:@"你没有摄像头"delegate:nilcancelButtonTitle:@"Drat!"otherButtonTitles:nil];
[alertshow];
}
3:实现UIImagePickerControllerDelegate (保存拍摄的照片)
//拍摄完成后,要执行的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//得到图片
UIImage *image=[infoobjectForKey:UIImagePickerControllerOriginalImage];
/**
用于拍照时,图片存入相册
*/
#if 0
//图片存入相册
UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);
#endif
/**
单利传值,弹出下一个viewcontroller
*/
AZChoseImage *choseImage=[AZChoseImagedefaultChoseImage];
choseImage.image=image;
[selfdismissViewControllerAnimated:NOcompletion:nil];
[self.navigationControllerpushViewController:self.filterVCanimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
完整的代码:
#import "ViewController.h" #import "CustomViewController.h" #import "AZFliterViewController.h" #import "AZChoseImage.h" @interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate> @property (nonatomic,strong)UIImagePickerController *ipc; @property (nonatomic,strong)CustomViewController *customIpc; @property (nonatomic,strong)AZFliterViewController *filterVC; @end @implementation ViewController #pragma mark -- 懶加载 -(UIImagePickerController *)ipc { if (!_ipc) { _ipc=[UIImagePickerController new]; } return _ipc; } -(CustomViewController *)customIpc { if (!_customIpc) { _customIpc=[[CustomViewController alloc] init]; } return _customIpc; } -(AZFliterViewController *)filterVC { if(!_filterVC) { _filterVC=[[AZFliterViewController alloc] init]; } return _filterVC; } - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark -- 使用UIImagePickerController - (IBAction)takePhoto:(id)sender { //判断是否可以打开相机,模拟器此功能无法使用 if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { self.ipc.delegate=self; //是否可编辑 self.ipc.allowsEditing=YES; //摄像头 self.ipc.sourceType=UIImagePickerControllerSourceTypeCamera; [self presentViewController:self.ipc animated:YES completion:nil]; }else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil]; [alert show]; } } #pragma mark -- UIImagePickerControllerDelegate //拍摄完成后,要执行的方法 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { //得到图片 UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage]; /** 用于拍照时,图片存入相册 */ #if 0 //图片存入相册 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); #endif /** 单利传值,弹出下一个viewcontroller */ AZChoseImage *choseImage=[AZChoseImage defaultChoseImage]; choseImage.image=image; [self dismissViewControllerAnimated:NO completion:nil]; [self.navigationController pushViewController:self.filterVC animated:YES]; } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [self dismissViewControllerAnimated:YES completion:nil]; } #pragma mark -- 使用AVFoundation.framework框架自定义照相 - (IBAction)customTakePhoto:(id)sender { [self.navigationController pushViewController:self.customIpc animated:YES]; } #pragma mark -- 从相册中选取图片,然后使用滤镜 - (IBAction)chosePicAndChange:(id)sender { if (!self.ipc.delegate) { self.ipc.delegate=self; } [self presentViewController:self.ipc animated:YES completion:nil]; } @end
第二种:利用AVFoundation.framework框架,自定义照相
完整代码:
#import "CustomViewController.h" #import <AVFoundation/AVFoundation.h> /** 需要导入头文件:#import <AVFoundation/AVFoundation.h> */ @interface CustomViewController () /** 在AVFoundation框架下使用自定义照相需要的属性 */ //AVCaptureSession对象来执行输入设备和输出设备之间的数据传递 @property (nonatomic, strong) AVCaptureSession * session; //AVCaptureDeviceInput对象是输入流 @property (nonatomic, strong) AVCaptureDeviceInput * videoInput; //照片输出流对象 @property (nonatomic, strong) AVCaptureStillImageOutput * stillImageOutput; //预览图层,来显示照相机拍摄到的画面 @property (nonatomic, strong) AVCaptureVideoPreviewLayer * previewLayer; #pragma mark -- 定义相机的展示 //切换前后镜头的按钮 @property (nonatomic, strong) UIBarButtonItem * changeButton; //拍照按钮 @property (nonatomic, strong) UIButton * takePhotoButton; //放置预览图层的View @property (nonatomic, strong) UIView * cameraShowView; @end @implementation CustomViewController - (void)viewDidLoad { [super viewDidLoad]; //初始化自定义相机的各实例 [self initialSession]; [self createCustomCaramView]; self.view.backgroundColor=[UIColor whiteColor]; } - (void) viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if (self.session) { [self.session startRunning]; } [self createCameraLayer]; } - (void) viewDidDisappear:(BOOL)animated { [super viewDidDisappear: animated]; if (self.session) { [self.session stopRunning]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark -- 自定义照相 /** 初始化自定义照相的相关实例 */ - (void) initialSession { //01 创建session self.session = [[AVCaptureSession alloc] init]; // 设置采集质量 if([self.session canSetSessionPreset:AVCaptureSessionPresetPhoto]) { self.session.sessionPreset=AVCaptureSessionPresetPhoto; } //02 创建输入设备,[self fronCamera]方法会返回一个AVCaptureDevice对象,因为我初始化时是采用前摄像头, self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:nil]; //03 创建输出设备 /** 有四类输出设备: 1: AVCaptureMovieFileOutput to output to a movie file (输出一个 视频文件) 2: AVCaptureVideoDataOutput if you want to process frames from the video being captured (可以采集数据从指定的视频中) 3: AVCaptureAudioDataOutput if you want to process the audio data being captured (采集音频) 4: AVCaptureStillImageOutput if you want to capture still images with accompanying metadata (采集静态图片) */ self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init]; // 这是输出流的设置参数AVVideoCodecJPEG参数表示以JPEG的图片格式输出图片 NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil]; [self.stillImageOutput setOutputSettings:outputSettings]; //04 添加输入输出设备到session中 if ([self.session canAddInput:self.videoInput]) { [self.session addInput:self.videoInput]; } if ([self.session canAddOutput:self.stillImageOutput]) { [self.session addOutput:self.stillImageOutput]; } } #pragma mark -- 获取设备(前 后 摄像头) - (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]; } #pragma mark -- 创建自定义照相上的按键以及view -(void)createCustomCaramView { _changeButton =[[UIBarButtonItem alloc] initWithTitle:@"调换摄像头" style:UIBarButtonItemStylePlain target:self action:@selector(toggleCamera)]; self.navigationItem.rightBarButtonItem=_changeButton; _takePhotoButton=[UIButton buttonWithType:UIButtonTypeSystem]; [_takePhotoButton setTitle:@"点击拍照" forState:UIControlStateNormal]; _takePhotoButton.frame=CGRectMake(0, 400, self.view.bounds.size.width,50); [_takePhotoButton addTarget:self action:@selector(shutterCamera) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:_takePhotoButton]; _cameraShowView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 400)]; _cameraShowView.backgroundColor=[UIColor grayColor]; [self.view addSubview:_cameraShowView]; } #pragma mark -- 切换镜头的按键方法 - (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); } } } #pragma mark -- 拍照按键响应事件 - (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)); }]; } #pragma mark -- 创建显示层 - (void) createCameraLayer { //如果不允许相机拍照,则返回 // 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]]; } } @end