1

“img”实际上是一个带有 URL 的字符串,但我实际上也将它用作文件名

NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:img];

NSURL *url = [NSURL URLWithString:img];
NSData *imageData = [NSData dataWithContentsOfURL:url];  

[imageData writeToFile:storePath atomically:TRUE];

在我的视图控制器中,我得到了这个:

UIImage *img = [[UIImage alloc] initWithContentsOfFile:self.initialImg];
if(img == nil) NSLog(@"image is nil");
[self.image setImage:img];

"initialImg" 是一个 NSString,其 url 与 "img" 中的相同。我还用另一个字符串(如 test.png)更改了“img”和“initialImg”,但这也不起作用。

它打印出“图像为零”,不知道为什么它是零......

编辑:

现在我得到了:

        NSURL *url = [NSURL URLWithString:img];
    NSData *imageData = [NSData dataWithContentsOfURL:url]; 

    UIImage *uiImage=[UIImage imageWithData:imageData];

    NSData *pngData = UIImagePNGRepresentation(uiImage);
    NSString *documentsPath  = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; 
    [pngData writeToFile:filePath atomically:YES];

在 viewDidLoad 函数的另一个视图控制器中:

    UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"image.png"];
    if(img == nil) NSLog(@"image is nil");

   [self.image setImage:img];

它仍然显示“图像为零”,我更改了网址,但它们是正确的

4

2 回答 2

0

因为 initWithContentsOfFile:你应该给出整个文件路径。我认为您只提供文件名。
试用案例

NSString *initialImg= @"test.png";
NSString *imagePath = [[NSBundle mainBundle]pathForResource:initialImg ofType:@"png"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:imagePath];
if(img == nil) NSLog(@"image is nil");
[self.image setImage:img];

否则你可以使用

self.image =[UIImage imageNamed:@"test.png"]

但这会导致性能问题

回答你的问题

//Write image data into document directory  

NSData *pngData = UIImagePNGRepresentation(image);
NSString *documentsPath  = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file


 // Read from directory using same file path 
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];
于 2013-03-07T14:34:58.937 回答
0

我想这对你来说已经足够了......

NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:img];

NSURL *url = [NSURL URLWithString:img];
NSData *imageData = [NSData dataWithContentsOfURL:url];

[imageData writeToFile:storePath atomically:TRUE];

在 viewDidLoad
// 你需要storePath而不是 url

NSData *imageData = [NSData dataWithContentsOfFile:storePath];
UIImage *image = [UIImage imageWithData:imageData];
于 2013-03-07T15:20:51.397 回答