【问题标题】:Memory issue in using UIImagePNGRepresentation使用 UIImagePNGRepresentation 时的内存问题
【发布时间】:2012-02-22 03:59:48
【问题描述】:

我发现这个模块很麻烦。我从 Photolibrary 导入了 100 多张图像,将它们保存在不同名称的文档目录中。正如预期的那样,我在不寻常的地方遇到了记忆问题。似乎 UIImagePNGRepresenation 正在缓存文件。因此,当我对 300 多个图像运行以下过程时,我看到“总字节数”在 3.00 GB 范围内,并且由于内存而崩溃(在分配工具中测试)。我已经粘贴了下面的代码。这段代码有什么替代方法吗

-(void)something
{
   NSData *data=nil;
   for (int i=0; i<numberOfImages; i++) {
    
    @autoreleasepool {
        
        UIImage *image=[UIImage imageNamed:[NSString stringWithFormat:@"image%d.png",i]];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingString:@"directoryname"];
        
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"image%d.png",i]];
        
        //convert image into .png format
        data=UIImagePNGRepresentation(image);
        [data writeToURL:[NSURL URLWithString:fullPath] atomically:NO];
      }
   }
   data=nil;
}

【问题讨论】:

    标签: memory uiimage uiimagepngrepresentation


    【解决方案1】:

    缓存来自[UIImage imageNamed:],而不是UIImagePNGRepresentation()。改为这样做:

    NSString *imageName = [NSString stringWithFormat:@"image%d.png", i];
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    
    ...
    

    【讨论】:

    • 没有。它不起作用。我尝试使用 [UIImage imageWithContentsOfFile:]、[[UIImage alloc]initWithContentsOfFile:]。问题在于将 UIImage 转换为 NSData 期间。我检查了上述大约 15 次
    • 好吧,好吧,因为你没有使用这些图像,而且它们一开始是 png,为什么不直接复制它们呢? [NSFileManager copyItemAtPath:toPath:error:]
    • 好主意..!我现在检查一下
    • 不,它不起作用。资产 URL 与正常 URL 不同。
    • 您可以使用 ALAssetRepresentation 复制原始数据。缺点是照片通常是 JPEG,而不是 PNG。
    【解决方案2】:

    我将此问题邮寄给 Apple,他们要求我在每次分配之间引入睡眠周期。在分配前添加睡眠。

    【讨论】:

    • 我也试过了,但没有帮助..请提供其他方法来解决这个问题...提前致谢
    【解决方案3】:

    我通过发送 4 通道图像(RGBA 或 RGBX)而不是 3 通道图像 (RGB) 来解决此问题。

    您可以检查是否有机会更改图像的参数。

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 2011-05-05
      • 2014-10-08
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2010-10-04
      • 2015-04-27
      相关资源
      最近更新 更多