iOS 使用UIImagePickerController 拍照

瘦欲@ 提交于 2020-03-14 11:24:58

    在项目开发的过程中,我们经常会使用的iPhone 或者 iPad 的拍照功能,比如给用户设置头像,一般都会用到拍照功能。我们可以使用UIImagePickerController 类来调用iPhone的摄像头进行拍照或者录视频。iOS 已经为我们封装好了UIImagePickerController ,使用很简单,让我们不用花费很多时间就可以调用拍照功能。使用UIImagePickerController时,需要实现UIImagePickerController协议。

     在xib中添加一个按钮,绑定按钮的响应事件,在响应事件中添加如下代码:

UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; 
   //判断是否有摄像头
   if(![UIImagePickerController isSourceTypeAvailable:sourceType])
    {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;   // 设置委托
    imagePickerController.sourceType = sourceType;
    imagePickerController.allowsEditing = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];  //需要以模态的形式展示
    [imagePickerController release];
    记得要实现UIImagePickerControllerDelegate 中 的- ( void )imagePickerController:( UIImagePickerController *)picker didFinishPickingMediaWithInfo:( NSDictionary *)info 和  

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 两个方法,分别时拍照完成的时候调用 和 取消拍照的时候调用。代码如下:

#pragma mark -
#pragma mark UIImagePickerController Method
//完成拍照
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (image == nil)
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [self performSelector:@selector(saveImage:) withObject:image];
    
}
//用户取消拍照
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//将照片保存到disk上
-(void)saveImage:(UIImage *)image
{

    NSData *imageData = UIImagePNGRepresentation(image);
    if(imageData == nil)
    {
        imageData = UIImageJPEGRepresentation(image, 1.0);
    }
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    _fileName = [[[formatter stringFromDate:date] stringByAppendingPathExtension:@"png"] retain];
    
    
    NSURL *saveURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:_fileName];
    
    [imageData writeToURL:saveURL atomically:YES];
    
    
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!