ios 调用系统照片库/拍照/录像

作者: devchena | 来源:发表于2015-10-27 08:40 被阅读5784次

    在iOS中要拍照和录制视频最简单的方法就是使用UIImagePickerController。UIImagePickerController继承于UINavigationController,我们可以用它来选取照片,还可以用来拍照和录制视频。

    要用UIImagePickerController来拍照或者录制视频通常可以分为如下步骤:

    1. 创建UIImagePickerController对象。
    2. 指定拾取源,平时选择照片时使用的拾取源是照片库或者相簿,此刻需要指定为摄像头类型。
    3. 指定摄像头,前置摄像头或者后置摄像头。
    4. 设置媒体类型mediaType,注意如果是录像必须设置,如果是拍照此步骤可以省略,因为mediaType默认包含kUTTypeImage(注意媒体类型定义在MobileCoreServices.framework中)
    5. 指定捕获模式,拍照或者录制视频。(视频录制时必须先设置媒体类型再设置捕获模式)
    6. 展示UIImagePickerController(通常以模态窗口形式打开)。
    7. 拍照和录制视频结束后在代理方法中展示/保存照片或视频。
    

    当然这个过程中有很多细节可以设置,例如是否显示拍照控制面板,拍照后是否允许编辑等等,通过上面的属性/方法列表相信并不难理解。

    下面用代码来展示下UIImagePickerController的使用:

    MyViewController

    .h

    #import "GetFilePath.h"
    
    @interface MyViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
    @end
    
    @implementation MyViewController
    //触发事件:拍照
    - (void)addCamera
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES; //可编辑
        //判断是否可以打开照相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            //摄像头
            //UIImagePickerControllerSourceTypeSavedPhotosAlbum:相机胶卷
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        } else { //否则打开照片库
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        [self presentViewController:picker animated:YES completion:nil];
    }
    
    //触发事件:录像
    - (void)addVideo
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            picker.videoQuality = UIImagePickerControllerQualityTypeMedium; //录像质量
            picker.videoMaximumDuration = 600.0f; //录像最长时间
            picker.mediaTypes = [NSArray arrayWithObjects:@"public.movie", nil];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"当前设备不支持录像功能" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
        //跳转到拍摄页面
        [self presentViewController:picker animated:YES completion:nil];
    }
    
    #pragma mark - UIImagePickerControllerDelegate
    
     //拍摄完成后要执行的代理方法
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
        NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
        BOOL success;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([mediaType isEqualToString:@"public.image"]) {
            //得到照片
            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                //图片存入相册
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
            }
            
            NSString *imagePath = [GetFilePath getSavePathWithFileSuffix:@"png"];
            success = [fileManager fileExistsAtPath:imagePath];
            if (success) {
                [fileManager removeItemAtPath:imagePath error:nil];
            }
            
            NSData *imageData = UIImagePNGRepresentation(image);
            [imageData writeToFile:imagePath atomically:YES]; //写入本地
            success = [fileManager fileExistsAtPath:imagePath];
            if (success) {
                 NSLog(@"图片写入成功,image路径:%@",imagePath);
            }
        } else if ([mediaType isEqualToString:@"public.movie"]) {
            NSString *videoPath = [GetFilePath getSavePathWithFileSuffix:@"mov"];
            success = [fileManager fileExistsAtPath:videoPath];
            if (success) {
                [fileManager removeItemAtPath:videoPath error:nil];
            }
            
            NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
            NSData *videlData = [NSData dataWithContentsOfURL:videoURL];
            [videlData writeToFile:videoPath atomically:YES]; //写入本地
            //存储数据
            success = [fileManager fileExistsAtPath:videoPath];
            if (success) {
                NSLog(@"media 写入成功,video路径:%@",videoPath);
            }
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    //进入拍摄页面点击取消按钮
    - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    

    GetFilePath

    .h

    #import <Foundation/Foundation.h>
    
    @interface GetFilePath : NSObject
    
    //获取要保存的本地文件路径
    + (NSString *)getSavePathWithFileSuffix:(NSString *)suffix;
    //获取录像的缩略图
    + (UIImage *)getVideoThumbnailWithFilePath:(NSString *)filePath;
    + (UIImage *)getImage:(NSString *)filePath;
    
    
    @end
    

    .m

    
    #import "GetFilePath.h"
    #import <MediaPlayer/MediaPlayer.h>
    #import <AVFoundation/AVFoundation.h>
    
    @implementation GetFilePath
    
    + (NSString *)getSavePathWithFileSuffix:(NSString *)suffix
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentPath = [paths objectAtIndex:0];
        
        NSDate *date = [NSDate date];
        //获取当前时间
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyyMMddHHmmss"];
        NSString *curretDateAndTime = [dateFormat stringFromDate:date];
        //获取用户userID
        NSDictionary *userDic= [[NSUserDefaults standardUserDefaults] objectForKey:UserInformation];
        //命名文件
        NSString *fileName = [NSString stringWithFormat:@"%@%@.%@",userDic[@"UserID"],curretDateAndTime,suffix];
        //指定文件存储路径
        NSString *filePath = [documentPath stringByAppendingPathComponent:fileName];
        
        return filePath;
    }
    
    + (UIImage *)getVideoThumbnailWithFilePath:(NSString *)filePath
    {
        MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];
        moviePlayer.shouldAutoplay = NO;
        UIImage *image = [moviePlayer thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
        return image;
    }
    
    + (UIImage *)getImage:(NSString *)filePath
    {
        NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        NSURL *url = [NSURL fileURLWithPath:filePath];
        AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:url options:options];
        AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
        generator.appliesPreferredTrackTransform = YES;
        generator.maximumSize = CGSizeMake(60, 60);
        CGImageRef imageRef = [generator copyCGImageAtTime:CMTimeMake(10, 10) actualTime:NULL error:nil];
        UIImage *image = [UIImage imageWithCGImage:imageRef];
        return image;
    }
    
    

    相关文章

      网友评论

      • 空转风:请问延迟拍照如何搞?
      • codeing小牛:大段的代码建议分几个小段, 现在这样感觉看起来有点不方便
        devchena:@codeing小牛 恩恩,好的,等项目上线我在整理下
      • odooerp:大哥有个问题:
        首先已经通过 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); 已经把照片存入相册了,后面的删除根本删除不了这张啊,因为拿不到路径,我试过,如果没有这句,紧紧是后面那些,是提示写入成功,但是相册中没有照片,这个如何解决呢?
        devchena:@odooerp 我记得以前可以在相册中删除的。换种方式,你可以尝试把照片写入指定路径
      • LIANGMIAOPM:GetFilePath这个类怎么处理?
        devchena:@ios菇凉 有时间我把代码补上
        devchena:@ios菇凉 其实这个也不重要,只要你获得图片数据,可以按自己的方式操作。
        devchena:@ios菇凉 getfilpath是我写的一个分类,作用是用“当前时间.png”作为文件名存在本地。
      • LIANGMIAOPM:NSString *videoPath = [GetFilePath getSavePathWithFileSuffix:@"mov"];
        ?????
      • LIANGMIAOPM:[GetFilePath getSavePathWithFileSuffix:@"png"];
        这个从何而来?

      本文标题:ios 调用系统照片库/拍照/录像

      本文链接:https://www.haomeiwen.com/subject/afyxhttx.html