Created
August 29, 2011 13:35
-
-
Save mtabini/1178403 to your computer and use it in GitHub Desktop.
PNG representation of NSImage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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