从相册获取相片或者照相需要实现UIImagePickerControllerDelegate, UINavigationControllerDelegate这两个协议,下面是具体的实现方法
- (void)addImage
{
UIActionSheet *actionsheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];
[actionsheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == actionSheet.cancelButtonIndex) {
}
switch (buttonIndex) {
case 0://打开照相机
[self takePhoto];
break;
case 1://打开相册
[self localPhoto];
break;
default:
break;
}
}
-(void)takePhoto//打开相机
{
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = sourceType;
[self presentViewController:picker animated:YES completion:nil];
}
}
-(void)localPhoto//本地相册
{
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
// 当选择的类型是图片
if ([type isEqualToString:@"public.image"]) {
// 把图片转化为NSData
UIImage *image = info[UIImagePickerControllerEditedImage];
NSData *data = UIImageJPEGRepresentation(image, 0.1);
// 图片的保存路径
NSString *documentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSFileManager *manager = [NSFileManager defaultManager];
// 将刚刚转化的图片放到沙盒中 并保存为png
[manager createDirectoryAtPath:documentsPath withIntermediateDirectories:YES attributes:nil error:nil];
NSString *imageName = [NSString stringWithFormat:@"/%@.png",[NSDate date]];
[manager createFileAtPath:[documentsPath stringByAppendingString:[NSString stringWithFormat:@"%@",imageName]] contents:data attributes:nil];
//得到选择后沙盒的路径
filePath = [[NSString alloc]initWithFormat:@"%@%@",documentsPath,imageName];
NSLog(@"%@",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}