iOS訪問相冊及拍照保存的實現實例
實現效果:
1、點擊訪問相冊按鈕,可以訪問系統相冊,選擇以後返回在imageView中顯示
2、點擊拍照,訪問攝像頭,實現以後保存在相冊中,返回在imageView中顯示
注意:拍照功能需要真機調試,模擬器無法實現
模擬器會有如下效果~彈出警告框
工程下載:github工程下載鏈接
下面是程序:注意此例中兩個button和UIimageView在stZ喎?/kf/ware/vc/" target="_blank" class="keylink">vcnlib2FyZNbQzO2806O7PC9wPg0KPHA+Vmlld0NvbnRyb2xsZXIuaDwvcD4NCjxwcmUgY2xhc3M9"brush:java;">
@interface ViewController : UIViewController
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(@已保存);
}