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

19

我有一个iPhone应用程序,使用UIImagePickerController。作为sourceType,我有:

  • UIImagePickerControllerSourceTypePhotoLibrary(照片图库)
  • UIImagePickerControllerSourceTypeCamera(相机拍摄)
  • UIImagePickerControllerSourceTypeSavedPhotosAlbum(已保存的照片)

所以用户可以从照片图库或相机照片中拍照或选择照片。

图片将显示在UIImageView中。如果用户关闭应用程序,则应保存图像。因此,对于文本字段,我使用NSUserDefaults。我知道,使用NSData将图像保存在NSUSerDefaults中不是一个好的方法,因此我想将图像保存/复制到一个由我的应用程序控制的文件夹中,类似于NSUserDefaults。

我该如何做?我想要保存它,然后我可以将文件路径写入我的NSUserDefaults并在应用程序启动时读取它。

提前感谢您的帮助和祝好!

4个回答

50

您可以在 UIImagePickerControllerDelegate 委托实现中使用以下代码

- (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];
    }
}

更新

XueYu 提供的 Swift 3.0 代码:

这里将图像保存为 JPEG 格式,但也可以保存为 PNG 格式。0.0 参数代表压缩质量最低,如果要获得最佳质量,请使用 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)        
}

3
我需要使用[info objectForKey:UIImagePickerControllerOriginalImage];而非UIImagePickerControllerEditedImage。 - Brody Robertson
确切地说,这取决于您是否允许编辑,picker.allowsEditing = YES; - khunshan
假设该图像为 PNG 格式(或至少不关心将图像保存为 PNG)。 - Andy

8

根据您想要保存的文件格式,您可以使用以下方法:

[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

或者

[UIImageJPEGRepresentation(image) writeToFile:path atomically:YES];

3
这是将UIImage保存到文档目录的代码。您可以在didFinishPickingImage代理方法中使用此代码:
// Create paths to output images
NSString  *pngPath = [NSHomeDirectory();
stringByAppendingPathComponent:@"Documents/Test.png"];
NSString  *jpgPath = [NSHomeDirectory();
stringByAppendingPathComponent:@"Documents/Test.jpg"];

// Write a UIImage to JPEG with minimum compression (best quality)
// The value 'image' must be a UIImage object
// The value '1.0' represents image compression quality as value from 0.0 to 1.0
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];

// Write image to PNG
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];

// Let's check to see if files were successfully written...

// Create file manager
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];

// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory();
stringByAppendingPathComponent:@"Documents"];

// Write out the contents of home directory to console
NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

编辑

您也可以使用:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

查找应用程序文档目录的路径,而不是NSHomeDirectory。


@iHS 我需要从API中检索图像并将其存储在应用程序中,我能否使用相同的代码保存图像? - arshad

2

更新knuku的Swift 3.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)        
}

这里图像被保存为JPEG格式,但你也可以将其保存为PNG格式。参数0.0代表压缩质量最低,如果想要获得最佳效果,请使用1.0。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接