1.新建viewController 拖入一個Button,添加點擊事件,使用代理方法
<UIActionSheetDelegate,UIImagePickerControllerDelegate>
2.代碼如下- (IBAction)DoChoose:(id)sender {
UIActionSheet *sheet;
//檢查是否有攝像頭功能 if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { sheet = [[UIActionSheet alloc] initWithTitle:@"選擇" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"從相冊選擇", nil]; } else { sheet = [[UIActionSheet alloc] initWithTitle:@"選擇" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"從相冊選擇", nil]; } sheet.tag=255; [sheet showInView:self.view]; }
//代理方法,啟用拍照或使用相冊功能 -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if (actionSheet.tag == 255) { NSUInteger sourceType = 0; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { switch (buttonIndex) { case 0: return; case 1: sourceType = UIImagePickerControllerSourceTypeCamera; break; case 2: sourceType = UIImagePickerControllerSourceTypePhotoLibrary; break; default: break; } } else { if (buttonIndex ==0) { return; } else { sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; } } UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; imagePickerController.delegate = self; imagePickerController.allowsEditing = YES; imagePickerController.sourceType = sourceType; [self presentViewController:imagePickerController animated:YES completion:^{}]; } }
//返回的圖片數據 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
//返回到主界面中 [picker dismissViewControllerAnimated:YES completion:^{}];
//獲取返回的圖片 UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//壓縮圖片 NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
//沙盒,准備保存的圖片地址和圖片名稱 NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"x.jpg"];
//將圖片寫入文件中 [imageData writeToFile:fullPath atomically:NO];
//通過路徑獲取到保存的圖片,可以在主界面上的image進行預覽 UIImage *saveImage = [[UIImage alloc]initWithContentsOfFile:fullPath]; [self.img1 setImage:saveImage];
//將圖片變為Base64格式,可以將數據通過接口傳給后台
NSData *data = UIImageJPEGRepresentation(saveImage, 1.0f);
NSString *baseString = [data base64Encoding];
}
//關閉拍照窗口 -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [self dismissViewControllerAnimated:YES completion:^{}]; }