gpt4 book ai didi

Swift - 选择 UIImage 的像素颜色 - 内存崩溃

转载 作者:行者123 更新时间:2023-11-28 16:10:51 25 4
gpt4 key购买 nike

我想在 Swift 3 中选择 UIImage 的特定像素的颜色,这个方法被调用了 ~10k 次。

 func pixelColour(_ pixelPosition: CGPoint) {

if !CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height).contains(pixelPosition) {
return false
}


let pointX = trunc(pixelPosition.x);
let pointY = trunc(pixelPosition.y);

let cgImage = self.cgImage;
let width = self.size.width;
let height = self.size.height;

let colorSpace = CGColorSpaceCreateDeviceRGB();
let bytesPerPixel = 4;
let bytesPerRow = bytesPerPixel * 1;
let bitsPerComponent = 8;
let pixelData = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)

let context = CGContext(data: pixelData, width: 1, height: 1, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)

context?.setBlendMode(CGBlendMode.copy);
context?.translateBy(x: -pointX, y: pointY-CGFloat(height));

// This line takes too much memory, how to release memory here?
context?.draw(cgImage!, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)));




print("\(pixelData[0]) \(pixelData[1]) \(pixelData[2]) ")
pixelData.deallocate(capacity: 4)


}

不幸的是,似乎没有释放内存,因为它在检查 ~500 像素后崩溃。我该如何解决这个问题?

最佳答案

您没有说明 pixelColour 是如何调用的,但我认为它处于某种循环中。如果是这样,请使用 autoreleasepool{...} 调用围绕您对 pixelColour 的重复调用,以便每次通过循环释放累积的内存:

let p = // next CGPoint
autoreleasepool {
pixelColour(p)
}

关于Swift - 选择 UIImage 的像素颜色 - 内存崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39579620/

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