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

发布于 2024-10-16 16:49:16 字数 570 浏览 4 评论 0原文

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

  • UIImagePickerControllerSourceTypePhotoLibrary
  • UIImagePickerControllerSourceTypeCamera
  • UIImagePickerControllerSourceTypeSavedPhotosAlbum

,因此用户可以制作照片或从照片或相机照片中的照片库中选择一张照片。

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

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

预先感谢您&此致。

I have an iPhone application using a UIImagePickerController. As sourceType I have

  • UIImagePickerControllerSourceTypePhotoLibrary
  • UIImagePickerControllerSourceTypeCamera
  • UIImagePickerControllerSourceTypeSavedPhotosAlbum

so the user can make a photo or select one from the photo library from the photos or camera photos.

The image will be displayed in a UIImageView. The image should be saved if the user closes the app. So for text fields, I use NSUserDefaults. I know, it is not a good way to save the image inside the NSUSerDefaults with NSData, so I want to save / copy the image to a folder which is controlled by my application similar to the NSUserDefaults.

How can I do this? I want to save it, and then I can write the path to the file into my NSUserDefaults and read it on startup of the application.

Thank you in advance & Best Regards.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

美胚控场 2024-10-23 16:49:16

中使用以下代码

- (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 的 UIImagePickerControllerDelegate 委托实现UPD

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)        
}

You can use the following code in UIImagePickerControllerDelegate delegate implementation

- (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 code by 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)        
}
不弃不离 2024-10-23 16:49:16

根据您要保存的文件格式,您可以使用

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

OR

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

Depending on the file format you want to save, you can use

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

OR

[UIImageJPEGRepresentation(image) writeToFile:path atomically:YES];
沩ん囻菔务 2024-10-23 16:49:16

这是将 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];

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

This is the code to save the UIImage into the document directory. You can use this code in didFinishPickingImage delegate method:

// 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]);

EDIT

You can also use:

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

to find the path to your application document directory, instead of NSHomeDierctory.

栀梦 2024-10-23 16:49:16

更新 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。

Update knuku's answer for 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)        
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文