如何将UIImage保存到文件?


Answers:


129

当然,您可以在应用程序的documents文件夹中创建子文件夹。您NSFileManager通常会这样做。

您用于UIImagePNGRepresentation将映像转换为NSData并将其保存到磁盘。

// Create path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

核心数据与将映像保存到磁盘无关。


通过使用UIImagePNGRepresentation,您将丢失所有方向信息。

1
那么如何保存图像而不丢失信息?
波兰时间

@Pol您可以将其另存为UIImageJPEGRepresentation或自己修复方向,链接stackoverflow.com/questions/3554244/…
user1210182

26

在Swift 3中

// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/MyImageName.png"

// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)

3
不再有效-你需要使用.write() throws
安德鲁ķ


17

上面的方法很有用,但是它们并不能回答您有关如何保存在子目录中或如何从UIImagePicker获取图像的问题。

首先,必须指定您的控制器在.m或.h代码文件中实现图像选择器的委托,例如:

@interface CameraViewController () <UIImagePickerControllerDelegate>

@end

然后,实现委托的imagePickerController:didFinishPickingMediaWithInfo:方法,从那里可以从图像选择器中获取照片并保存(当然,您可以使用另一个类/对象来处理保存,但是我只显示代码)在方法内部):

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // get the captured image
    UIImage *image = (UIImage *)info[UIImagePickerControllerOriginalImage];


    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *imageSubdirectory = [documentsDirectory stringByAppendingPathComponent:@"MySubfolderName"];

    NSString *filePath = [imageSubdirectory stringByAppendingPathComponent:@"MyImageName.png"];

    // Convert UIImage object into NSData (a wrapper for a stream of bytes) formatted according to PNG spec
    NSData *imageData = UIImagePNGRepresentation(image); 
    [imageData writeToFile:filePath atomically:YES];
}

如果要另存为JPEG图像,则最后3行为:

NSString *filePath = [imageSubdirectory stringByAppendingPathComponent:@"MyImageName.jpg"];

// Convert UIImage object into NSData (a wrapper for a stream of bytes) formatted according to JPG spec
NSData *imageData = UIImageJPEGRepresentation(image, 0.85f); // quality level 85%
[imageData writeToFile:filePath atomically:YES];

12
extension UIImage {
    /// Save PNG in the Documents directory
    func save(_ name: String) {
        let path: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let url = URL(fileURLWithPath: path).appendingPathComponent(name)
        try! UIImagePNGRepresentation(self)?.write(to: url)
        print("saved image at \(url)")
    }
}

// Usage: Saves file in the Documents directory
image.save("climate_model_2017.png")

6
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];

其中path是要写入的文件的名称。


4

首先,您应该获得Documents目录

/* create path to cache directory inside the application's Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"fileName"];

然后,您应该将照片保存到文件中

NSData *photoData = UIImageJPEGRepresentation(photoImage, 1);
[photoData writeToFile:filePath atomically:YES];

4

在Swift 4.2中:

// Create path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
    // Save image.
    do {
       try image.pngData()?.write(to: filePath, options: .atomic)
    } catch {
       // Handle the error
    }
}

2

在Swift 4中:

// Create path.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
    // Save image.
    do {
       try UIImagePNGRepresentation(image)?.write(to: filePath, options: .atomic)
    }
    catch {
       // Handle the error
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.