Skip to content

Instantly share code, notes, and snippets.

@chbeer
Last active December 23, 2015 17:29
Show Gist options
  • Save chbeer/6669565 to your computer and use it in GitHub Desktop.
Save chbeer/6669565 to your computer and use it in GitHub Desktop.
Stores a screenshot of a window to disk as PNG
@implementation NSWindow (JSTalk)
- (BOOL) storeWindowImageToFile:(NSString*)fileName
{
CGWindowID windowID = (CGWindowID)[self windowNumber];
CGWindowImageOption imageOptions = kCGWindowImageDefault;
CGWindowListOption singleWindowListOptions = kCGWindowListOptionIncludingWindow;
CGRect imageBounds = CGRectNull;
CGImageRef windowImage = CGWindowListCreateImage(imageBounds, singleWindowListOptions, windowID, imageOptions);
NSMutableData *data = [NSMutableData data];
CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)data, kUTTypePNG, 1, NULL);
if ( destination ) {
CGImageDestinationAddImage( destination, windowImage, (__bridge CFDictionaryRef)@{
(NSString*)kCGImageDestinationLossyCompressionQuality: [NSNumber numberWithDouble:0.7],
(NSString*)kCGImageDestinationBackgroundColor: (id)[[NSColor clearColor] CGColor]
});
CGImageDestinationFinalize( destination );
CFRelease(destination);
} else {
return NO;
}
fileName = [fileName stringByExpandingTildeInPath];
return [data writeToFile:fileName atomically:NO];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment