CGContextDrawImage吃了我的记忆,任何内存泄漏?

时间:2011-07-18 06:36:23

标签: cocoa memory-management memory-leaks cgcontext

我正在使用Cocoa和Xcode4在Mac OS X 10.6上开发Mac应用程序,从相机缓冲区获取图像后,我需要获取图像的原始数据。这是代码:

- (void)captureOutput:(QTCaptureOutput *)captureOutput didOutputVideoFrame:(CVImageBufferRef)videoFrame withSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection
{
    CVImageBufferRef imageBufferRef;
    @synchronized (self) {
        imageBufferRef = CVBufferRetain(videoFrame);
    }
    if (imageBufferRef) {
        CIImage *originalImage = [CIImage imageWithCVImageBuffer:imageBufferRef];

        // Denoise
        [noiseReductionFilter setValue:originalImage forKey:@"inputImage"];
        CIImage *denoisedImage = [noiseReductionFilter valueForKey:@"outputImage"];
        NSCIImageRep *denoisedImageRep = [NSCIImageRep imageRepWithCIImage:denoisedImage];
        //

        NSImage *image = [[NSImage alloc] initWithSize:[denoisedImageRep size]];
        [image addRepresentation:denoisedImageRep];

        NSUInteger width = CVPixelBufferGetWidth(imageBufferRef);
        NSUInteger height = CVPixelBufferGetHeight(imageBufferRef);
        NSUInteger bytesPerRow = CVPixelBufferGetBytesPerRow(imageBufferRef);
        NSUInteger bitsPerSample = [denoisedImageRep bitsPerSample];

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

        CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)[image TIFFRepresentation], NULL);
        CGImageRef imageRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);

        [image release];

        unsigned char *rawData = malloc(height * width * 4);

        NSUInteger bitsPerComponent = 8;

        CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big);
        CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
        CGContextRelease(context);
        CGImageRelease(imageRef);
        CGColorSpaceRelease(colorSpace);

        free(rawData);

        CVBufferRelease(imageBufferRef);
    }
}

(我删除了一些代码使其看起来更清晰,我删除的代码保证不会泄漏任何内存。我很抱歉这些变量没有完美命名。)

问题在于:

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);

我认为在“CGContextRelease(context);”之后,应该释放内存。但是在我运行这个应用程序之后,内存很快就会耗尽 - 每秒钟在Real Mem中增加大约20MB的额外内存。

我试图删除这行CGContextDrawImage,内存似乎正常工作 - 每秒只增加几十或几百KB。

我使用Instrument来分析我的应用程序,但没有发现内存泄漏。

任何人都可以帮我解决这个问题吗?我已经工作了很多天但没有找到任何解决方案,甚至没有找到原因。

如果您能给我任何建议来改进此代码或修复其中的任何其他问题,我将不胜感激。即使我删除该行,它仍然会缓慢地占用内存,但如果我阻止整个方法,内存将不会耗尽,所以我相信代码中仍然存在一些问题。

我是新手,请原谅我,如果我的帖子格式不正确,我的英语不好。

1 个答案:

答案 0 :(得分:1)

感谢ersentekin给出的提示,我现在可以关闭这个问题了。答案是:

发现问题!它符合排名" CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)[image TIFFRepresentation], NULL);" - 我没有发布" source"!