ios 调用系统照片库/拍照/录像
2015-10-27 本文已影响5784人
devchena
在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;
}