如何将UIImage保存到文件?

问题描述 投票:101回答:9

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

iphone objective-c ios uiimage
9个回答
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];

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


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)

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

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

11
投票
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];

3
投票

在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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.