ios 如何将 UIImage 保存到文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11592313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I save a UIImage to a file?
提问by user1542660
If I have a UIImage
from an imagePicker, how can I save it to a subfolder in the documents directory?
如果我有一个UIImage
来自 imagePicker 的文件,我如何将它保存到文档目录中的子文件夹中?
回答by DrummerB
Of course you can create subfolders in the documents folder of your app. You use NSFileManager
to do that.
当然,您可以在应用程序的文档文件夹中创建子文件夹。你习惯NSFileManager
这样做。
You use UIImagePNGRepresentation
to convert your image to NSData and save that to disk.
您用于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];
Core Data has nothing to do with saving images to disk by the way.
顺便说一下,Core Data 与将图像保存到磁盘无关。
回答by NatashaTheRobot
In Swift 3:
在 Swift 3 中:
// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/MyImageName.png"
// Save image.
UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)
回答by dasblinkenlight
You have to construct a representation of your image as a particular format(say, JPEG or PNG), and then call writeToFile:atomically:
on the representation:
您必须将图像表示为特定格式(例如 JPEG 或 PNG),然后调用writeToFile:atomically:
该表示:
UIImage *image = ...;
NSString *path = ...;
[UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];
回答by Alex the Ukrainian
The above are useful, but they don't answer your question of how to save in a subdirectory or get the image from a UIImagePicker.
以上内容很有用,但它们没有回答您如何保存在子目录中或从 UIImagePicker 获取图像的问题。
First, you must specify that your controller implements image picker's delegate, in either .m or .h code file, such as:
首先,您必须在 .m 或 .h 代码文件中指定您的控制器实现图像选择器的委托,例如:
@interface CameraViewController () <UIImagePickerControllerDelegate>
@end
Then you implement the delegate's imagePickerController:didFinishPickingMediaWithInfo: method, which is where you can get the photograph from the image picker and save it (of course, you may have another class/object that handles the saving, but I'll just show the code inside the method):
然后你实现委托的 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];
}
If you want to save as JPEG image, the last 3 lines would be:
如果要另存为 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];
回答by neoneye
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")
回答by Maggie
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:path atomically:YES];
where path is the name of the file you want to write it to.
其中 path 是您要将其写入的文件的名称。
回答by lu yuan
First you should get the Documents directory
首先你应该得到 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"];
Then you should save the photo to the file
然后你应该将照片保存到文件中
NSData *photoData = UIImageJPEGRepresentation(photoImage, 1);
[photoData writeToFile:filePath atomically:YES];
回答by Torianin
In Swift 4.2:
在 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
}
}
回答by Samo
In Swift 4:
在 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
}
}