以下代码段使用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
创建,并且没有内存泄漏,但是{{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)的方式。