如何将 UIImage 保存到文件中?

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

98958 次浏览

你必须使用 以特定格式构造图像的表示形式(比如 JPEG 或 PNG) ,然后调用 writeToFile:atomically:表示:

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

当然,你可以在应用程序的文档文件夹中创建子文件夹。

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

CoreData 与将映像保存到磁盘没有任何关系。

首先,您应该获得“文档”目录

/* 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];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];

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

以上内容很有用,但是它们不能回答您的问题,即如何保存在子目录中或从 UIImagePicker 获取图像。

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

@interface CameraViewController () <UIImagePickerControllerDelegate>


@end

然后实现委托的 imagePickerController: did FinishPickingMediaWithInfo: 方法,在这里你可以从图像选择器获取照片并保存它(当然,你可能有另一个类/对象来处理保存,但我只是显示方法中的代码) :

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

雨燕3:

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


// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)
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")

雨燕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
}
}

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