Save CGImageRef to PNG file errors? (ARC Caused?)

后端 未结 1 1699
天命终不由人
天命终不由人 2021-01-16 09:49

This code used to work, however I think Xcode\'s new ARC may have killed it

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    CGDir         


        
1条回答
  •  清酒与你
    2021-01-16 10:04

    The code you posted wouldn't work either with or without ARC, because you need to expand the tilde in the path name before passing it.

    The code you posted also was leaking the items returned by CGDisplayCreateImage and CGImageDestinationCreateWithURL. Here's an example that works and doesn't 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);
    }
    

    0 讨论(0)
提交回复
热议问题