iOS 调用拍照、选择本地相册、上传功能---未完善。

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:^{}];
}
原文地址:https://www.cnblogs.com/youyuan1980/p/5341753.html