iOS访问相册及拍照保存的实现实例
实现效果:
1、点击访问相册按钮,可以访问系统相册,选择以后返回在imageView中显示
2、点击拍照,访问摄像头,实现以后保存在相册中,返回在imageView中显示
注意:拍照功能需要真机调试,模拟器无法实现
模拟器会有如下效果~弹出警告框
工程下载:github工程下载链接
下面是程序:注意此例中两个button和UIimageView在storyboard中添加;
ViewController.h
@interface ViewController : UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageShow;
@end
ViewController.m
#pragma mark - 拍照并保存
- (IBAction)takePhotoAction:(id)sender {
BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
if (!isCamera) { //若不可用,弹出警告框
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"无可用摄像头" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
return;
}
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
/**
* UIImagePickerControllerSourceTypePhotoLibrary ->所有资源文件夹
UIImagePickerControllerSourceTypeCamera ->摄像头
UIImagePickerControllerSourceTypeSavedPhotosAlbum ->内置相册
*/
imagePicker.delegate = self; //设置代理,遵循UINavigationControllerDelegate,UIImagePickerControllerDelegate协议
[self presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark - 访问相册
- (IBAction)browseAlbum:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark - 协议方法的实现
//协议方法,选择完毕以后,呈现在imageShow里面
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSLog(@"%@",info); //UIImagePickerControllerMediaType,UIImagePickerControllerOriginalImage,UIImagePickerControllerReferenceURL
NSString *mediaType = info[@"UIImagePickerControllerMediaType"];
if ([mediaType isEqualToString:@"public.image"]) { //判断是否为图片
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageShow.image = image;
//通过判断picker的sourceType,如果是拍照则保存到相册去
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
}
// else 当然可能是视频,这里不作讨论~方法是类似的~
[picker dismissViewControllerAnimated:YES completion:nil];
}
//此方法就在UIImageWriteToSavedPhotosAlbum的上方
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
NSLog(@"已保存");
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/zsk_zane/article/details/47283297