iPhone - UIImagePickerController -> 将图像保存到应用程序文件夹

标签 iphone objective-c uiimage uiimagepickercontroller

我有一个使用 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/

相关文章:

iphone - 任何想法如何从同一工作区下的其他项目加载 Nib - IOS?

iphone - 使用 Parse 从应用程序内打开和关闭推送通知

objective-c - 如何访问文档文件夹

objective-c - 文档表不响应键盘事件

Swift:UIImage——找不到接受提供的参数的 'init' 的重载

ios - 保存到用户照片库静默失败

swift - 如何编程更改使用 Interface Builder 创建的 UIImageView 中图像的高度/宽度?

iphone - 在 iPhone 通讯录中创建群组

java - Android音译获取API_KEY的方法

iphone - 动画导航栏标题