如何将UIImage保存到文件?

时间:2012-07-21 12:47:36

标签: iphone objective-c ios uiimage

如果我有一个来自imagePicker的UIImage,如何将其保存到文档目录中的子文件夹?

9 个答案:

答案 0 :(得分:128)

当然,您可以在应用的文档文件夹中创建子文件夹。您可以使用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];

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

答案 1 :(得分:25)

在Swift 3中:

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

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

答案 2 :(得分:24)

您必须construct a representation of your image as a particular format(例如,JPEG或PNG),然后在代表处调用writeToFile:atomically:

UIImage *image = ...;
NSString  *path = ...;
[UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];

答案 3 :(得分:15)

以上内容很有用,但它们没有回答您如何保存在子目录中或从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];

答案 4 :(得分:10)

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

答案 5 :(得分:6)

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

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

答案 6 :(得分: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];

答案 7 :(得分: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
    }
}

答案 8 :(得分:1)

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