【发布时间】:2018-02-08 05:02:05
【问题描述】:
我一直在尝试将 UIImages 保存并加载到我的应用程序的 Documents 文件夹或最好的临时文件夹中(因此每次我的应用程序关闭时,图像都会被删除),但它们无法正常工作。我尝试了三种方法,但只有第三种方法有效,我想知道正确的方法是什么?我非常感谢任何帮助。
//First Approach, to save and load later, Doesn't work.
//Saving the image
NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask]
lastObject];
NSString*fileDirectoryStr = [[documentsDirectoryURL path] stringByAppendingPathComponent:@"E1BG.png"];
NSURL *url = [NSURL URLWithString:fileDirectoryStr];
//Saving either as Jpeg
[UIImagePNGRepresentation(finalFG) writeToFile:fileDirectoryStr atomically:YES];
//Or as PNG, because I need the transparent part to be kept transparent but non of them work.
[UIImageJPEGRepresentation(finalFG, 1.0) writeToFile:fileDirectoryStr atomically:YES];
//Loading image
UIImage *loadedBGImg = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
//Returns nil
//Second approach.
//Saving the image
NSArray*pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsPath = [pathArray objectAtIndex:0];
NSString* fileDirectoryStr = [documentsPath stringByAppendingPathComponent:@"E1FG.png"];
//Again saving either as Jpeg
[UIImagePNGRepresentation(finalFG) writeToFile:fileDirectoryStr atomically:YES];
//Or as PNG, because I need the transparent part to be kept transparent but non of them work.
[UIImageJPEGRepresentation(finalFG, 1.0) writeToFile:fileDirectoryStr atomically:YES];
NSURL *url1 = [NSURL URLWithString:fileDirectoryStr];
//Loading image
UIImage *loadedImg = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]];
//Third approach, Works but doesnt seem to be very efficient.
NSString *tmpDirectory = NSTemporaryDirectory();
//Save
NSString *tmpFileStrFG = [tmpDirectory stringByAppendingPathComponent:@"E1FG.png"];
NSURL *urlFG = [NSURL URLWithString:tmpFileStrFG];
NSData *imgDataFG = UIImagePNGRepresentation(finalFG);
[imgDataFG writeToURL:urlFG atomically:YES];
//Load
UIImage *ImggFG = [UIImage imageWithData: imgDataFG];
【问题讨论】:
-
您想从文档目录中保存和检索图像。你的问题对吗?
-
不,我的意思是为什么前两种方法不起作用?我究竟做错了什么?我是否在第三种方法中正确使用我的应用程序中的临时文件夹来做到这一点? @MikeAlter
-
保存方法二看起来不错。请检查 fetch url 以加载图像,我不确定方法一个
-
第二个根本不起作用。您能否提供一种适用于所有 ios 更新(包括 ios 11)的有效方法? @MikeAlter
标签: ios objective-c uiimage nsdata nsfilemanager