【问题标题】:Core Image and memory leak, swift 3.0Core Image 和内存泄漏,swift 3.0
【发布时间】:2017-05-11 01:41:45
【问题描述】:

我有问题我尝试在一些扩展名为 3000x2000 的图像上使用过滤器,当我这样做时 RAM 上限和应用程序出现致命错误“didReceiveMemoryWarning”。

 func setFilters(images: [UIImage]) -> [UIImage] {
    let filter = CIFilter(name: "CIColorControls")!
    filter.setValue(2.0, forKey: kCIInputContrastKey)

    let context = CIContext(options: nil)

    var result = [UIImage]()

    for img in images {
        let newImage = autoreleasepool(invoking: { () -> UIImage in
            filter.setValue(CIImage(image: img)!, forKey: kCIInputImageKey)

            let ciImage = filter.outputImage!
            let cgImage = context.createCGImage(ciImage, from: ciImage.extent)


            return UIImage(cgImage: cgImage!, scale: img.scale, orientation: img.imageOrientation)
        })

        result.append(newImage)
    }

    return result
}

【问题讨论】:

    标签: swift memory-leaks ios10 core-image


    【解决方案1】:

    这不是内存泄漏;那是你实际上使用了太多的内存。导致问题的不是 CIFilter 的使用;事实上,您正试图将所有这些巨大的 UIImage 对象保存在内存中的单个数组中:

    var result = [UIImage]()
    // ...
    result.append(newImage)
    

    不要那样做。

    【讨论】:

    • 那么如何在过滤后存储图像,我做了10张照片并尝试为它们过滤并保存到手机。
    • 您可以保存它们,但您需要立即保存每一个,而不是等到过滤掉其中的 10 个。你没有那个记忆。同样,您不能拍摄 10 张照片并将它们全部保存在内存中。最初将每个文件保存到磁盘。仅加载 一张 照片进行处理,对其进行处理,保存已处理的照片,然后发布两张照片。重复。很简单。
    • 如果我将用“result.append(newImage)”注释行,程序将崩溃 didReceiveMemoryWarning 的 bcs。
    • 因为你还是从images: [UIImage]开始的。您没有空间容纳一组图像。
    • 另外这一行是对内存的极大浪费:UIImage(cgImage: cgImage!, scale: img.scale, orientation: img.imageOrientation) 你已经有了 CGImage。这就是结束。那是你的照片数据。将那个保存到照片库中。
    猜你喜欢
    • 2017-06-09
    • 2013-11-24
    • 2020-03-19
    • 2017-11-25
    • 2012-11-16
    • 1970-01-01
    • 2012-02-09
    • 2016-03-28
    • 2020-04-29
    相关资源
    最近更新 更多