Saving NSImage as JPEG ( or anything else)

// Output as JPEG
NSImage *image4 = [[NSImage alloc] initWithSize:NSMakeSize(320.0f, 240.0f)];
[image4 lockFocus];

[[NSColor redColor] setFill];
[[NSColor blueColor] setStroke];

[rectPath setLineWidth:10.0f];
[rectPath stroke];
[rectPath fill];

//        NSArray *representations = [image4 representations];
//        
//        NSData *jpegData = [NSBitmapImageRep representationOfImageRepsInArray:representations
//                                                                    usingType:NSJPEGFileType
//                                                                   properties:[NSDictionary dictionaryWithObjectsAndKeys:@0.8f, NSImageCompressionFactor, nil]];

// Code above doesn't work.
//        (lldb) po representations
//        <__NSArrayI 0x104801d10>(
//                                 <NSCGImageSnapshotRep:0x104802fe0 cgImage=<CGImage 0x104802f00>>
//                                 )
//
// the presentation doesn't return an appropriate instance of NSImageRep concrete interface.

NSBitmapImageRep *jpegImageRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0.0f, 0.0f, 320.0f, 240.0f)];
NSData *jpegData = [jpegImageRep representationUsingType:NSJPEGFileType
                                              properties:[NSDictionary dictionaryWithObject:@0.8f forKey:NSImageCompressionFactor]];

[image4 unlockFocus];


[jpegData writeToFile:[NSString stringWithFormat:@"%@/redRectangle-comparison.jpg", desktop]
                atomically:YES];

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: