以下代码片段保存 CIImage
使用 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
来释放它
如果该行带有 #if 1
更改为#if 0
,UIImage
直接从 CIImage
创建并且没有内存泄漏,但是 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];
@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 ( more info )。
关于ios7 - 无法在 iOS 上将 CIImage 保存到文件而不发生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826755/