我使用CGBitMapContext()将色彩空间转换为ARGB并获取像素数据值,我为位图上下文分配空间,并在完成后释放它,但我仍然看到Instruments中的内存泄漏。我认为我可能做错了什么,因此如果有任何帮助,将不胜感激。
下面是ARGBBitmapContext函数
func createARGBBitmapContext(width: Int, height: Int) -> CGContext {
var bitmapByteCount = 0
var bitmapBytesPerRow = 0
//Get image width, height
let pixelsWide = width
let pixelsHigh = height
bitmapBytesPerRow = Int(pixelsWide) * 4
bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh)
let colorSpace = CGColorSpaceCreateDeviceRGB()
// Here is the malloc call that Instruments complains of
let bitmapData = malloc(bitmapByteCount)
let context = CGContext(data: bitmapData, width: pixelsWide, height: pixelsHigh, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
// Do I need to free something here first?
return context!
}这里是我使用上下文以UInt8s列表的形式检索所有像素值的地方(也是内存泄漏的地方)。
extension UIImage {
func ARGBPixelValues() -> [UInt8] {
let width = Int(self.size.width)
let height = Int(self.size.height)
var pixels = [UInt8](repeatElement(0, count: width * height * 3))
let rect = CGRect(x: 0, y: 0, width: width, height: height)
let context = createARGBBitmapContext(inImage: self.cgImage!)
context.clear(rect)
context.draw(self.cgImage!, in: rect)
var location = 0
if let data = context.data {
while location < (width * height) {
let arrOffset = 3 * location
let offset = 4 * (location)
let R = data.load(fromByteOffset: offset + 1, as: UInt8.self)
let G = data.load(fromByteOffset: offset + 2, as: UInt8.self)
let B = data.load(fromByteOffset: offset + 3, as: UInt8.self)
pixels[arrOffset] = R
pixels[arrOffset+1] = G
pixels[arrOffset+2] = B
location += 1
}
free(context.data) // Free the data consumed, perhaps this isn't right?
}
return pixels
}
}Instruments报告1.48MiB的malloc错误,这对于我的图像大小(540x720)是正确的。我释放了数据,但显然这是不正确的。
我应该提一下,我知道你可以将nil传递给CGContext init (它将管理内存),但我更好奇为什么使用malloc会产生问题,还有什么我应该知道的(我更熟悉Obj-C)。
发布于 2019-09-14 09:52:30
因为CoreGraphics不是由ARC处理的(像所有其他C库一样),所以你需要用自动释放来包装你的代码,即使在Swift中也是如此。尤其是如果你不在主线程上(如果涉及到CoreGraphics,你就不应该在主线程上....userInitiated或更低为宜)。
func myFunc() {
for _ in 0 ..< makeMoneyFast {
autoreleasepool {
// Create CGImageRef etc...
// Do Stuff... whir... whiz... PROFIT!
}
}
}对于那些关心你的人来说,你的Objective-C也应该像这样包装:
BOOL result = NO;
NSMutableData* data = [[NSMutableData alloc] init];
@autoreleasepool {
CGImageRef image = [self CGImageWithResolution:dpi
hasAlpha:hasAlpha
relativeScale:scale];
NSAssert(image != nil, @"could not create image for TIFF export");
if (image == nil)
return nil;
CGImageDestinationRef destRef = CGImageDestinationCreateWithData((CFMutableDataRef)data, kUTTypeTIFF, 1, NULL);
CGImageDestinationAddImage(destRef, image, (CFDictionaryRef)options);
result = CGImageDestinationFinalize(destRef);
CFRelease(destRef);
}
if (result) {
return [data copy];
} else {
return nil;
}详情请参见this answer。
https://stackoverflow.com/questions/43339784
复制相似问题