1

我正在使用以下代码保存我的图像---

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]


NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];


NSString *filePath= [NSString stringWithFormat:@"%@/%@.jpg", DOCUMENTS_FOLDER,caldate];
imageurl = [NSURL fileURLWithPath:filePath];
dataImage = UIImagePNGRepresentation(myimage);
[dataImage writeToFile:filePath atomically:YES];

imageurl 打印如下

file://localhost/Users/varmab/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/E2EDF729-4684-465B-8BE3-2C0ACFA2EC03/Documents/2013-03-18%2012:02:31%20+ 0000.jpg

现在,我想显示保存的图像,即图像存储在上述文件路径中

我尝试了以下代码:

//1st process:
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageurl]];

//2nd process:
NSURL *urlString =imageurl;
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:urlString]])];
UIImage *image = [UIImage imageWithData:imageData];

//3rd process:
NSData * imageData = [[NSData alloc] initWithContentsOfURL:imageurl ];
self.testingImageView.image = [UIImage imageWithData: imageData];

请指导我,我做错了吗?

4

3 回答 3

4

你为什么不直接使用这个方法:

 - (id)initWithContentsOfFile:(NSString *)path

它已经在UIImage课堂上可用。

[self.testingImageView setImage: [[UIImage alloc] initWithContentsOfURL:imageurl]];

试试这个,如果你再次遇到同样的问题,请告诉我。

注意:检查图像 url 是否与保存该图像时获得的旧图像 url 相似。

于 2013-03-18T13:50:42.077 回答
1

这将为您提供文档目录下所有文件的路径;

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];

        NSLog(@"files array %@", filePathsArray);

您可以使用以下代码获取 filePathsArray 中每个对象的路径;

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:0]]; 
于 2013-03-18T13:51:10.007 回答
0

快速
获取文档目录的路径,将图像存储在同一位置,您可以检索。

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

if let image = UIImage(named: "example.png") {
    if let data = UIImagePNGRepresentation() {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}
于 2017-02-25T02:22:26.260 回答