【问题标题】:How to add images in Array ios?如何在 Array ios 中添加图像?
【发布时间】:2023-03-21 14:10:01
【问题描述】:

下图编辑图像后,当我单击共享/保存按钮时,如何在数组中添加图像。我应该显示在 tableview 中,并且已经保存在本地。

【问题讨论】:

  • 您必须将图像数据存储在数组而不是图像中。
  • 你能解释一下如何在我想在tableview中显示的数组中保存和检索
  • 你可以有一个图像数组 'var images_array=[UIImage]()' 或一个数据数组 'var data_array=[NSData]()' 并像这样检索图像 'let image=UIImage (数据:data_array[i])'。
  • 您想将这些数组图像显示到另一个 vc 或同一个 vc 内吗?
  • 我想显示另一个视图控制器

标签: ios objective-c ios7 ios5 ios7.1


【解决方案1】:

您可以像这样将 UIImage 转换为 NSData:

如果是 PNG 图片

UIImage *image = [UIImage imageNamed:@"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];

如果是JPG图片

UIImage *image = [UIImage imageNamed:@"imageName.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

将 imageData 添加到数组中:

[self.arr addObject:imageData];

从 NSData 加载图像:

UIImage *img = [UIImage imageWithData:[self.arr objectAtIndex:0]];

【讨论】:

    【解决方案2】:

    不要将图像存储到数组或字典中,除非您想创建缓存,但缓存应该在将来逐出它们的内容。
    您正在使用的移动设备即使功能强大,也没有与您的 Mac 相同的硬件。
    内存是一种有限的资源,应该通过判断来管理。
    如果您出于性能原因想临时缓存这些图像,可以使用NSCache,基本上就像可变字典一样工作,但它是线程安全的。
    如果您想将它们保存在本地也可以,但只需将它们的路径保留在数组中即可。

    - (NSString*) getDocumentsPath {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsPath = paths[0]; //Get the document directory
        return documentsPath;
    }
    
    - (NSString*) writePNGImage: (UIImage*) image withName: (NSString*) imageName {
        NSString *filePath = [[self getDocumentsPath] stringByAppendingPathComponent:imageName]; // Add file name
        NSData *pngData = UIImagePNGRepresentation(image);
        BOOL saved = [pngData writeToFile:filePath atomically:YES]; //Write the file
        if (saved) {
            return filePath;
        }
        return nil;
    }
    
    - (UIImage*) readImageAtPath:(NSString*) path {
        NSData *pngData = [NSData dataWithContentsOfFile:path];
        UIImage *image = [UIImage imageWithData:pngData];
        return image;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-07
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2017-08-08
      • 1970-01-01
      相关资源
      最近更新 更多