【问题标题】:Can't save CIImage to file on iOS without memory leaks无法在没有内存泄漏的情况下将 CIImage 保存到 iOS 上的文件
【发布时间】:2014-11-07 17:20:58
【问题描述】:

以下 sn-p 代码使用 UIImageCIImage 保存到磁盘。

- (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];
}

但是,即使调用CGImageRelease 释放CGImageRef,它也会泄露它

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

【问题讨论】:

    标签: ios7 memory-leaks uikit core-image


    【解决方案1】:

    将保存的内容封装在自动释放池中:

    - (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) 的方式。

    【讨论】:

    猜你喜欢
    • 2014-04-03
    • 2012-01-02
    • 1970-01-01
    • 2021-12-19
    • 2013-02-09
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多