使用UIImage时,图像无法从URL保存

时间:2013-03-07 14:22:31

标签: ios objective-c

“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”中的URL相同。我还用另一个字符串如test.png更改了“img”和“initialImg”,但这也不起作用。

打印出“image is nil”并且不确定为什么它是nil ...

修改

现在我得到了:

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

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

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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 而不是网址

NSData *imageData = [NSData dataWithContentsOfFile:storePath];
UIImage *image = [UIImage imageWithData:imageData];