1
- (void)takeScreenShot {
    CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
    CGImageWriteToFile(screenShot, [@"~/code/screenshot.png" stringByExpandingTildeInPath]);
}

BOOL CGImageWriteToFile(CGImageRef image, NSString *path) {
    CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
    if (!destination) {
        NSLog(@"Failed to create CGImageDestination for %@", path);
        return NO;
    }

    CGImageDestinationAddImage(destination, image, nil);

    if (!CGImageDestinationFinalize(destination)) {
        NSLog(@"Failed to write image to %@", path);
        CFRelease(destination);
        return NO;
    }

    CFRelease(destination);
    return YES;
}

Failed to create CGImageDestination for /Users/"username"/Library/Containers/"bundleidentifier"/Data/code/screenshot.png

So no destination is returned. Preferably I would like to write to ~/code/screenshot.png but if it is something with sandboxing it is also ok to write to "sandbox"

How do I write a screenshot to a file that I can access later?

I have adapted code from Saving CGImageRef to a png file?

Community
  • 1
  • 1
user12345625
  • 398
  • 6
  • 17

1 Answers1

4
@import MobileCoreServices; // or `@import CoreServices;` on Mac
@import ImageIO;

BOOL CGImageWriteToFile(CGImageRef image, NSString *path) {
    CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
    if (!destination) {
        NSLog(@"Failed to create CGImageDestination for %@", path);
        return NO;
    }

    CGImageDestinationAddImage(destination, image, nil);

    if (!CGImageDestinationFinalize(destination)) {
        NSLog(@"Failed to write image to %@", path);
        CFRelease(destination);
        return NO;
    }

    CFRelease(destination);
    return YES;
}

You have to add ImageIO and MobileCoreServices to your project and also have to add header.

sp309
  • 150
  • 1
  • 10