我有一个使用 UIImagePickerController
的 iPhone 应用程序。作为 sourceType
我有
- UIImagePickerControllerSourceTypePhotoLibrary
- UIImagePickerControllerSourceTypeCamera
- UIImagePickerControllerSourceTypeSavedPhotosAlbum
因此用户可以从照片或相机照片中制作照片或从照片库中选择一张照片。
图像将显示在 UIImageView 中。如果用户关闭应用程序,则应保存图像。所以对于文本字段,我使用 NSUserDefaults
。我知道,使用 NSData 将图像保存在 NSUSerDefaults 中并不是一个好方法,所以我想将图像保存/复制到一个由我的应用程序控制的文件夹,类似于 NSUserDefaults。
我该怎么做?我想保存它,然后我可以将文件的路径写入我的 NSUserDefaults
并在应用程序启动时读取它。
提前致谢并致以最诚挚的问候。
最佳答案
可以在UIImagePickerControllerDelegate
委托(delegate)实现中使用如下代码
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
//obtaining saving path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"latest_photo.png"];
//extracting image from the picker and saving it
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:@"public.image"]){
UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
NSData *webData = UIImagePNGRepresentation(editedImage);
[webData writeToFile:imagePath atomically:YES];
}
}
UPD
Swift 3.0 代码 XueYu
here the image is saved as jpeg but you can also save it as png. the 0.0 parameter stands for compression and it's the lowest quality, if you want to get the best use 1.0.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//obtaining saving path
let fileManager = FileManager.default
let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
let imagePath = documentsPath?.appendingPathComponent("image.jpg")
// extract image from the picker and save it
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
try! UIImageJPEGRepresentation(pickedImage, 0.0)?.write(to: imagePath!)
}
self.dismiss(animated: true, completion: nil)
}
关于iPhone - UIImagePickerController -> 将图像保存到应用程序文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4957972/