gpt4 book ai didi

swift - CIImage内存未释放

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:22 24 4
gpt4 key购买 nike

我正在尝试拍摄一系列图像,同时混合 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
}
}

如代码注释中所述,我希望在 firstImage 和 secondImage 中分配的内存在创建它们的范围结束时被释放。因为它们都是在 while 循环中创建的,所以我希望它们在该循环结束时被释放,然而,这似乎没有发生。但是这里没有内存泄漏,因为当 blendImages 函数完成时,内存被适本地释放(但是,这为时已晚,因为代码可能会运行数百或数千张图像,从而使应用程序消耗几个 TB 的数据,然后才被释放)。如果有人能看到我的代码中的缺陷以及如何提高内存效率,我们将不胜感激。

最佳答案

你应该使用 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
}
}

你可以查看这个post获取更多信息。

关于swift - CIImage内存未释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53839394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com