无法在没有内存泄漏的情况下将CIImage保存到iOS上的文件 [英] Can't save CIImage to file on iOS without memory leaks

查看:345
本文介绍了无法在没有内存泄漏的情况下将CIImage保存到iOS上的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码片段使用 UIImage CIImage 保存到磁盘。

The following snippet of code save a CIImage to disk using an UIImage.

- (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

However, it leaks the CGImageRef even when it is released by calling CGImageRelease

如果 #if 1 更改为 #if 0 UIImage 直接从创建CIImage 且没有内存泄漏,但 UIImage 未保存到磁盘

If the line with #if 1 is changed to #if 0, the UIImage is created directly from the CIImage and there are no memory leaks, but then the UIImage is not saved to disk

推荐答案

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

Wrap the saving inside an autorelease pool:

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

另请注意,我更新了您检索文档的方式适用于iOS 8的目录(更多信息)。

Also note that I updated how you were retrieving the Documents directory to work for iOS 8 (more info).

这篇关于无法在没有内存泄漏的情况下将CIImage保存到iOS上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆