_mediaUI = [[UIImagePickerController alloc] init]; _mediaUI.delegate = self;
- (IBAction)photographBtn:(id)sender { UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { _mediaUI.sourceType = sourceType; _mediaUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeImage , nil]; _mediaUI.allowsEditing = YES; [self presentViewController:_mediaUI animated:YES completion:nil]; }else{ NSLog(@"模拟其中无法打开照相机,请在真机中使用"); } } - (IBAction)albumBtn:(id)sender { _mediaUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; _mediaUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeSavedPhotosAlbum]; _mediaUI.allowsEditing = NO; [self presentViewController:_mediaUI animated:YES completion:nil]; } - (IBAction)cancelBtn:(id)sender { [self.navigationController popViewControllerAnimated:YES]; } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = nil; NSString *path = [NSString stringWithFormat:@"%@",[info objectForKey:UIImagePickerControllerReferenceURL]]; NSArray *typeArray = [path componentsSeparatedByString:@"="]; NSString *type = [typeArray lastObject]; if(picker.sourceType == UIImagePickerControllerSourceTypeCamera) { image = [info objectForKey:UIImagePickerControllerOriginalImage]; } else { NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) { image = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage]; } } NSData *data = nil; if ([type isEqualToString:@"JPG"]) { data = UIImageJPEGRepresentation(image, 1.0); }else{ data = UIImagePNGRepresentation(image); } // NSString *fileNameTemp = typeArray[1]; // NSString *filename = [NSString stringWithFormat:@"%@.%@",[[fileNameTemp componentsSeparatedByString:@"&"] firstObject],type]; // //图片保存的路径 // //这里将图片放在沙盒的documents文件夹中 // NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; // //文件管理器 // NSFileManager *fileManager = [NSFileManager defaultManager]; // //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png // [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil]; // [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil]; [picker dismissViewControllerAnimated:YES completion:nil]; _headPortrait.image = [[UIImage imageWithData:data] getRoundImage]; } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; }
时间: 2024-10-17 09:18:53