//
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//样式
imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
imagePicker.allowsEditing = YES;
[self presentViewController:imagePicker animated:YES completion:nil];
//方法功能:实现相机的委托,判断选择的是一个视频还是图片,并写入文件
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// NSLog(@"相机回调");
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; //文件类型
NSData *sourceData;
static NSInteger sourceType;
if ([mediaType isEqualToString:/*@"public.image"*/ (NSString *)kUTTypeImage]) {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
sourceData = UIImageJPEGRepresentation(image, 0.1f);//image得到NSData 第二个参数为压缩质量
sourceType = 0;
//UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
else if ([mediaType isEqualToString:/*@"public.movie"*/ (NSString *)kUTTypeMovie]) {
NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
sourceData = [NSData dataWithContentsOfURL:sourceURL];
if ([sourceData length] == 0)
{
[self showMessage:NSLocalizedString(@"选择的视频文件不存在.", nil) withStatus:(LAStatusError)];
[picker dismissViewControllerAnimated:YES completion:nil];
return;
}
sourceType = 1;
}
NSString *sourceFilePath;
// NSFileManager *fileManager = [NSFileManager defaultManager];
switch (sourceType) {
case 0: {
sourceFilePath = [[[NSFileManager defaultManager] imageCacheFolderUrl] path];
NSString *identifier = [NSString stringWithFormat:@"%ld", (long)[[NSDate date]timeIntervalSince1970]];
NSString *filePathComponent = [NSString stringWithFormat:@"%@.png", identifier];
sourceFilePath = [sourceFilePath stringByAppendingPathComponent:filePathComponent];
[sourceData writeToFile:sourceFilePath atomically:YES];
//获取图片文件
// NSData *data = [NSData dataWithContentsOfFile:sourceFilePath];
}
break;
case 1: {
sourceFilePath = [[[NSFileManager defaultManager] videoCacheFolderUrl] path];
NSString *identifier = [NSString stringWithFormat:@"%ld", (long)[[NSDate date]timeIntervalSince1970]];
NSString *filePathComponent = [NSString stringWithFormat:@"%@.3gp", identifier];
sourceFilePath = [NSString stringWithFormat:@"%@/%@", sourceFilePath, filePathComponent];
[sourceData writeToFile:sourceFilePath atomically:YES];
}
break;
default:
break;
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
//方法功能:退出图片库或者相机界面
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}