iOS開發-iOS調用相機調用相簿【將圖片儲存到本地相簿】,ios-ios
設定頭部代理
<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
1.調用相機
檢測自拍是否可用
- (BOOL)isFrontCameraAvailable{ return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];}
檢測後置網路攝影機是否可用
- (BOOL)isRearCameraAvailable{ return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];}
調用相機
///調用相機- (void)persentImagePicker{ if (!_imagePickerG) { ///初始化相機 _imagePickerG = [[UIImagePickerController alloc]init]; ///代理 _imagePickerG.delegate = self; } // 前面的網路攝影機是否可用 if ([self isFrontCameraAvailable]) { _imagePickerG.sourceType = UIImagePickerControllerSourceTypeCamera; } // 後面的網路攝影機是否可用 else if ([self isFirstResponder]){ _imagePickerG.sourceType = UIImagePickerControllerSourceTypeCamera; } else{ [SVProgressHUD showErrorWithStatus:@"沒有相機可用~"]; return; } ///允許拍照後裁剪 _imagePickerG.allowsEditing = YES; [self.navigationController presentViewController:_imagePickerG animated:YES completion:nil];}
2.調用相簿
///調用本地相簿- (void)persentImagePicker{ if (!_imagePickerG) { ///初始化相機 _imagePickerG = [[UIImagePickerController alloc]init]; ///代理 _imagePickerG.delegate = self; } ///相簿 _imagePickerG.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; _imagePickerG.allowsEditing = YES; [self.navigationController presentViewController:_imagePickerG animated:YES completion:nil];}
3.代理事件
///取消選擇圖片(拍照)- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [picker dismissViewControllerAnimated:YES completion:nil];}
///選擇圖片完成(從相簿或者拍照完成)- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{ UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];///原圖 //擷取修剪後的圖片 UIImage *imageUp = [info objectForKey:UIImagePickerControllerEditedImage];}
4.將圖片儲存到本地
///儲存圖片到本地相簿-(void)imageTopicSave:(UIImage *)image{ UIImageWriteToSavedPhotosAlbum(image, self, @selector(image: didFinishSavingWithError: contextInfo:), nil);}- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{ if (error == nil) { } else{ ///圖片未能儲存到本地 }}