iOS - 将多张图片保存到文档文件夹

标签 ios camera nsdocumentdirectory

我有这段代码,这段代码用于将图像保存到 Documents 文件夹。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,        NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory  stringByAppendingPathComponent:@"savedImage.png"];
    UIImage *image = imageView.image; // imageView is my image from camera
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:savedImagePath atomically:NO]; 

我正在寻找一种能够保存多个图像的方法,因为这个方法一直在写 savedImage.png 名称。

我不介意在 google 或其他网站上寻找它,但我需要知道它叫什么,因为用错误的关键字寻找真的会耽误世界:-)

干杯

最佳答案

您需要在第三行更改附加到图像文档目录路径的文件名。每次您都需要使用一个尚未使用的不同名称。 NSFileManager 具有查看文件是否存在的方法,因此您可以构造一个文件名,然后测试它是否存在于该位置,如果存在,则增加重复计数并尝试下一个。

如果 num 是您在某处定义并保留的整数,这样您就知道您认为您使用的最后一个(并且您已在某处初始化为 1)。

// your code to get the directory here, as above

NSFileManager *fm = [NSFileManager ...]

do {
   savedImagePath = [documentsDirectory stringByAppendingPathComponent: 
        [NSString stringWithFormat: @"%@-%d.png", @"savedImage", num]];
   num += 1; // for next time

  if ( ![fm fileExistsAtPath: savedImagePath] )
  {
      // save your image here using savedImagePath
      exit;
  }
} while ( //some kind of test for maximum tries/time or whatever )

您必须查找语法以获取 NSFileManager 实例并且确切的文件存在方法签名,但这就是它的要点。

关于iOS - 将多张图片保存到文档文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10670978/

相关文章:

objective-c - 如何设置部分 curl 模式不隐藏工具栏?

ios - 从 TableView (Swift) 中删除行时出错

拍照后,Android 的相机不会返回我的应用程序

objective-c - 显示来自 NSDocumentDirectory 的照片

iphone - 如何在 UITableView 中为节标题的高度变化设置动画?

ios - 如何在 Swift View Controller 中访问私有(private) Objective-C 变量?

ios - 如何在 Objective-C 中更改 ImageView 的持续时间

android - Android 位图出现奇怪的 OutOfMemoryError : Why does showing and then hiding the containing View avoid it?

ios - 删除并重新安装 iOS 应用程序后保留的文档目录

swift - 从文档目录获取图像而不是文件路径 Swift 3