iOS选取图片与拍照保存图片
2017-08-01 本文已影响165人
JohnayXiao
//遵守协议,第一个必需遵守,第二个我不确定
<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
- (void)funcChooseFromPhotoAlbum {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//设置代理
imagePicker.delegate = self;
//允许编辑
imagePicker.allowsEditing = true;
//设置图片源
[imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//模态弹出IamgePickerView
[self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)funcChooseFromCamera {
// UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
isUseCamera = YES;
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//设置代理
imagePicker.delegate = self;
//允许编辑
imagePicker.allowsEditing = true;
//设置图片源
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
//模态弹出IamgePickerView
[self presentViewController:imagePicker animated:YES completion:nil];
}else {
NSLog(@"模拟器不支持拍照功能");
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
UIImage* outputImage = [info objectForKey:UIImagePickerControllerEditedImage];
if (outputImage == nil) {
outputImage = [info objectForKey:UIImagePickerControllerOriginalImage];
}
NSData *headData = UIImagePNGRepresentation(outputImage);
NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//拼接文件绝对路径
NSString *path = [documents stringByAppendingPathComponent:@"header.png"];
//保存
[headData writeToFile:path atomically:YES];
headView.headImage.image = outputImage;
// UIImageWriteToSavedPhotosAlbum 这个方法,默认保存到系统相机胶卷,但是@selector后面的方法 必须是这种格式: - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
//保存图片到系统相册
if (isUseCamera) {
isUseCamera = NO;
outputImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(outputImage, self, nil, nil);
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存失败");
}
else {
NSLog(@"保存成功");
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:nil];
}