下面的代码片段保存了一个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
, the 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];
}
}
另请注意,我更新了您检索 Documents 目录以适用于 iOS 8 的方式(更多信息 https://developer.apple.com/library/ios/technotes/tn2406/_index.html).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)