无法在没有内存泄漏的情况下将CIImage保存到iOS上的文件

时间:2014-09-13 19:17:34

标签: ios7 memory-leaks uikit core-image

以下代码段使用CIImageUIImage保存到磁盘。

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSString* filename = @"Test.png";

    UIImage *image = [UIImage imageNamed:filename];

    // make some image processing then store the output
    CIImage *processedImage = [CIImage imageWithCGImage:image.CGImage];

#if 1// save using context

    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgiimage = [context createCGImage:processedImage fromRect:processedImage.extent];
    image = [UIImage imageWithCGImage:cgiimage];

    CGImageRelease(cgiimage);

#else

    image = [UIImage imageWithCIImage:processedImage];

#endif

    // save the image

    NSString *filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[@"../Documents/" stringByAppendingString:filename]];

    [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
}

然而,即使通过调用CGImageRef释放CGImageRelease,它也会泄漏#if 1

enter image description here

如果#if 0的行更改为UIImage,则CIImage直接从UIImage创建,并且没有内存泄漏,但是{{1}没有保存到磁盘

1 个答案:

答案 0 :(得分:3)

将保存包装在自动释放池中:

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSString* filename = @"Test.png";

    UIImage *image = [UIImage imageNamed:filename];

    // make some image processing then store the output
    CIImage *processedImage = [CIImage imageWithCGImage:image.CGImage];

    @autoreleasepool {
        CIContext *context = [CIContext contextWithOptions:nil];
        CGImageRef cgiimage = [context createCGImage:processedImage fromRect:processedImage.extent];
        image = [UIImage imageWithCGImage:cgiimage];

        CGImageRelease(cgiimage);

        // save the image
        NSURL *documentsDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
        NSURL *fileURL = [documentsDir URLByAppendingPathComponent:filename];

        [UIImagePNGRepresentation(image) writeToURL:fileURL atomically:YES];
    }
}

另请注意,我更新了您检索Documents目录以适用于iOS 8(more info)的方式。