今天做项目用到的上传图片到服务器,现在来总结一下具体流程。
首先我们看下UIImagePickerControllerSourceTypePhotoLibrary:选取相册中的图像。图像选取控制器以该模式显示时会浏览系统照片库的根目录。
UIImagePickerControllerSourceTypeCamera:打开相机拍照选取图像。(对了,最近新出的IOS10需要对访问相册授权。)
在info.plist文件下添加 :
相机权限
<key>NSCameraUsageDescription</key>
<string>cameraDesciption</string>
相册权限
<key>NSPhotoLibraryUsageDescription</key>
<string>photoLibraryDesciption</string>
UIImagePickerController * imagepicker = [[UIImagePickerController alloc]init];
imagepicker.delegate = self;//代理
if (type == 2) {
imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagepicker.allowsEditing=YES;//允许编辑图片
}else{
imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
imagepicker.allowsEditing = YES;
}
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagepicker animated:YES completion:nil];
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
UIImage *image = info[UIImagePickerControllerOriginalImage];
[self saveImage:image WithName:@"userAvatar.jpg"];
[self.picButton setImage:image forState:UIControlStateNormal] ;//添加从相册选取的图片
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
NSData* imageData = UIImageJPEGRepresentation(tempImage,0.2f);
NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* totalPath = [documentPath stringByAppendingPathComponent:imageName];
//保存到 document
[imageData writeToFile:totalPath atomically:NO];
self.picPath = totalPath;
}