Save CGImageRef for PNG file errors? (Called by ARC?)

This code worked, but I think Xcode new ARC might have killed it

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { CGDirectDisplayID displayID = CGMainDisplayID(); CGImageRef image = CGDisplayCreateImage(displayID); //this is a screenshot (works fine) [self savePNGImage:image path:@"~/Desktop"]; } -(void)savePNGImage:(CGImageRef)imageRef path:(NSString *)path { NSURL *outURL = [[NSURL alloc] initFileURLWithPath:path]; //here xcode suggests using __bridge for CFURLRef? CGImageDestinationRef dr = CGImageDestinationCreateWithURL ((__bridge CFURLRef)outURL, (CFStringRef)@"public.png" , 1, NULL); CGImageDestinationAddImage(dr, imageRef, NULL); CGImageDestinationFinalize(dr); } 

This code returns an error:

ImageIO: image assignment CGImageDestinationAddImage parameter is nil

which I assume means that CGImageDestinationRef is not created correctly. I could not find an implementation for this, that the new Xcode does not give the same error, what am I doing wrong?

+1
source share
1 answer

The code you posted will not work with or without ARC, because before you pass it, you need to expand the tilde in the path name.

The code you provided also had leaks of elements returned by CGDisplayCreateImage and CGImageDestinationCreateWithURL . Here is an example that works and does not leak:

 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { CGDirectDisplayID displayID = CGMainDisplayID(); CGImageRef imageRef = CGDisplayCreateImage(displayID); //this is a screenshot (works fine) NSString *path = [@"~/Desktop/public.png" stringByExpandingTildeInPath]; [self savePNGImage:imageRef path:path]; CFRelease(imageRef); } - (void)savePNGImage:(CGImageRef)imageRef path:(NSString *)path { NSURL *fileURL = [NSURL fileURLWithPath:path]; CGImageDestinationRef dr = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypePNG , 1, NULL); CGImageDestinationAddImage(dr, imageRef, NULL); CGImageDestinationFinalize(dr); CFRelease(dr); } 
+4
source

All Articles