Skip to content

Instantly share code, notes, and snippets.

@shadowboy
Forked from mtabini/gist:1178403
Created July 1, 2012 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadowboy/3028094 to your computer and use it in GitHub Desktop.
Save shadowboy/3028094 to your computer and use it in GitHub Desktop.
PNG representation of NSImage
//
// GRAppDelegate.m
// Testme
//
// Created by Marco Tabini on 11-08-29.
// Copyright (c) 2011 Marco Tabini. All rights reserved.
//
#import "GRAppDelegate.h"
@implementation GRAppDelegate
@synthesize window = _window;
// Note this uses ARC. Modify as needed for traditional retain/release management
// Grab a screenshot from the main screen
- (NSImage *)captureImageForRect:(NSRect)rect {
CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:screenShot];
NSImage *result = [[NSImage alloc] init];
[result addRepresentation:imageRep];
return result;
}
- (NSData *) PNGRepresentationOfImage:(NSImage *) image {
// Create a bitmap representation from the current image
[image lockFocus];
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, image.size.width, image.size.height)];
[image unlockFocus];
return [bitmapRep representationUsingType:NSPNGFileType properties:Nil];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Take a screenshot
NSImage *screenshot = [self captureImageForRect:[[NSScreen mainScreen] frame]];
// Resize it to 50%. This will cause finalImage to contain a NSCGImageSnapshotRep
NSSize newSize = NSMakeSize(screenshot.size.width / 2, screenshot.size.height / 2);
NSImage *finalImage = [[NSImage alloc] initWithSize:newSize];
[finalImage lockFocus];
[screenshot drawInRect:NSMakeRect(0, 0, newSize.width, newSize.height)
fromRect:NSMakeRect(0, 0, screenshot.size.width, screenshot.size.height)
operation:NSCompositeSourceOver
fraction:1.0];
[finalImage unlockFocus];
// Now create a PNG representation of the image. This should work regardless
// of the format of its existing representations
NSData *pngRep = [self PNGRepresentationOfImage:finalImage];
// Write it to the desktop
[pngRep writeToFile:[@"~/Desktop/screenshot.png" stringByExpandingTildeInPath]
atomically:NO];
// Close app
[NSApp terminate:self];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment