【问题标题】:objective-c: failed to write image to documents directory目标-c:无法将图像写入文档目录
【发布时间】:2012-04-14 00:56:37
【问题描述】:

我正在使用这段代码尝试将图像保存到文档目录:

//FOR TESTING ON SIMULATOR 
UIImage* image = [UIImage imageNamed:@"ReceiptImage1.jpg"];
NSData *imageData = UIImagePNGRepresentation(image);
NSString* imageName = @"Receipt1Image1.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];        
[imageData writeToFile:fullPathToFile atomically:NO];

self.receiptImage1 = fullPathToFile;

self.receiptImageView1.image = [UIImage imageWithContentsOfFile:fullPathToFile];

NSLog(@"fullPathToFile %@", fullPathToFile);

但是,这段代码并未将 imageViews 图像设置为我尝试写入文档目录的收据图像。

谁能解释我做错了什么以及如何解决它?

谢谢,

杰克

【问题讨论】:

  • 你检查writeToFile:atomically:的返回值了吗?如果有错误,您可以使用writeToFile:options:error: 变体检查它是什么。
  • 另外,为什么您实际上需要将图像从应用程序包复制到文档目录?
  • 您在设备中检查过您的代码吗?因为模拟器不会逐行执行代码..[imageData writeToFile:fullPathToFile atomically:NO];方法需要一些时间将图像写入路径,所以尝试在一段时间后将图像加载到图像中
  • 您的代码运行良好。请查看 IBOutlet 以获取receiptImageView1。
  • @MrTJ 成功将图像保存到文档目录后,我将更改代码以从相机/照片中获取图像,这仅用于在模拟器上进行测试。谢谢大家。

标签: iphone objective-c ios uiimageview nsdocumentdirectory


【解决方案1】:

使用这个:

- (void)saveImage:(UIImage*)image:(NSString*)imageName{
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.

NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it

NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; //add our image to the path 

[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)

NSLog(@"image saved");}

【讨论】:

    【解决方案2】:

    先原子写入文件,再尝试:

    self.receiptImage1 = [UIImage imageWithContentsOfFile:fullPathToFile];
    self.receiptImageView1 = [UIImageView initWithImage:self.receiptImage1];
    

    【讨论】:

      【解决方案3】:

      如果已经存在文件,它可能不会保存到该路径。 (查看 API 文档,我记不清了。但为了保存,您应该添加如下内容:

          NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
          NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
          _exportPath = [documentsDirectoryPath stringByAppendingPathComponent:aFileName];  // may need to hang onto him
      
          if ([[NSFileManager defaultManager] fileExistsAtPath:_exportPath]) {
              [[NSFileManager defaultManager] removeItemAtPath:_exportPath
                                                         error:nil];
          }
      

      【讨论】:

        【解决方案4】:

        您可以采取以下方法

        -(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
            if ([[extension lowercaseString] isEqualToString:@"png"]) {
                [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
            } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
                [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
            } else {
                ALog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
            }
        }
        

        要保存图像,只需这样做:

        NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        [self saveImage:yourImage withFileName:@"Your Image Name" ofType:@"png" inDirectory:path];
        

        要加载图像,请实现此方法:

        -(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
        
            UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];
        
            return result;
        }
        

        然后像这样使用它:

        NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        yourImage.image = [self loadImage:@"Your Image Name" ofType:@"png" inDirectory:path];
        

        或者您可以简单地将您的图像设置为等于此方法返回的内容,而不是创建一个方法:

        NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        yourImage.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/Your Image Name.png", path]];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-25
          • 2018-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-14
          相关资源
          最近更新 更多