2

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

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

enter image description here

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

Lkopo
  • 4,798
  • 8
  • 35
  • 60
rraallvv
  • 2,875
  • 6
  • 30
  • 67

1 Answers1

3

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

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

Rick
  • 847
  • 8
  • 12
  • 1
    Even using @autoreleasepool does not solve the issue: http://stackoverflow.com/questions/32685756/memory-leak-in-cmsamplebuffergetimagebuffer – loretoparisi Sep 27 '15 at 17:40