CIIMAGE内存未发布



我试图拍摄一系列图像,当时混合x图像并产生新图像。这是我必须完成的代码:

static func blendImages(blendFrames: Int, blendMode: CIImage.BlendMode, imagePaths: [URL], completion: @escaping (_ progress: Double) -> Void) {
    var currentIndex = 0
    while currentIndex + blendFrames < imagePaths.count {            
        let currentSubset = Array(imagePaths[currentIndex..<(currentIndex + blendFrames)])
        var currentSubsetIndex = 0
        var firstImage: CIImage?
        while currentSubset.count > currentSubsetIndex + 1 {                
            if firstImage == nil { firstImage = CIImage(contentsOf: currentSubset[currentSubsetIndex]) } //First image allocated in memory
            if let secondImage = CIImage(contentsOf: currentSubset[currentSubsetIndex + 1]) {//Second image allocated in memory
                firstImage = firstImage?.blend(with: secondImage, blendMode: blendMode)
            } //Would expect secondImage to be freed from memory at this point, but it does not happen
            currentSubsetIndex += 1
        } 
        if let finalImage = firstImage {
            let bitMapRep = NSBitmapImageRep(ciImage: finalImage)
            let data = bitMapRep.representation(using: .jpeg, properties: [:])
            do {
                try data?.write(to: URL(fileURLWithPath: "Final-" + String(format: "%03d", currentIndex) + ".jpg"))
            } catch let error as NSError {
                print("Failed to write to disk: (error)")
            }
        }
        firstImage = nil //Would expect firstImage to be freed from memory at this point (or at beginning of next cycle in while-loop), but it does not happen
        currentIndex += 1
    }
}

和CIIMAGE blend功能的代码

extension CIImage {
    enum BlendMode: String {
        case Lighten = "CILightenBlendMode"
        case Darken = "CIDarkenBlendMode"
    }
    func blend(with image: CIImage, blendMode: BlendMode) -> CIImage? {
        let filter = CIFilter(name: blendMode.rawValue)!
        filter.setDefaults()
        filter.setValue(self, forKey: "inputImage")
        filter.setValue(image, forKey: "inputBackgroundImage")
        return filter.outputImage
    }
}

正如代码中的评论中所详细介绍的,我希望在创建范围的范围结束时释放出第一次图像和第二图的内存。由于它们都是在while-loop中创建的但是,要在该循环结束时释放,这似乎没有发生。但是这里没有内存泄漏,因为当blendImages函数完成后,已适当释放内存(但是,这为时已晚,因为代码可以通过数百或数千张图像运行,使该应用程序在其之前消耗了几个TBS释放)。如果有人可以看到我的代码中的缺陷以及如何使其更具记忆效率,这将是非常感谢的。

您应该使用 autoreleasepool函数强制其范围内的对象的释放。此功能将帮助您更精确地管理内存足迹。

static func blendImages(blendFrames: Int, blendMode: CIImage.BlendMode, imagePaths: [URL], completion: @escaping (_ progress: Double) -> Void) {
    var currentIndex = 0
    while currentIndex + blendFrames < imagePaths.count {
        autorelease {
            // your code
        }
        currentIndex += 1
    }
}

您可以检查此帖子以获取更多信息。

相关内容

  • 没有找到相关文章

最新更新