Mar 15

I was trying to do image manipulation like rotate/resize/convert image files. My application is a daemon running in the background various kind of services. While Qt’s QImage class provides robust functionality and is well enough to do image manipulations, problem here was the size of QtGui module which is around 7 Mb. I don’t like to load 7Mb of binary to memory for just few functions in QImage.

Cocoa’s NSImage seems the right candidate for such requirements.
For example, the following simple code does image resizing,

NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:srcData];
NSImage *scratch = [[[NSImage alloc] initWithSize:NSMakeSize(100, 100)] autorelease];
[scratch lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[rep drawInRect:NSMakeRect(0.0, 0.0, 100, 100)];
NSBitmapImageRep *output = [[[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0,0,100,100)] autorelease];
[scratch unlockFocus];

One important point to note in the above code is if you are trying to do lockFocus inside a Qt Core application(non-gui application), the lockFocus will throw an exception and results in application crash if unhandled.
Solution to this is to call NSApplicationLoad() inside main() or any place before you call lockFocus. This is required (or a call to [NSApplication sharedApplication]) for our application to have a window server connection for the lockFocus to work.

And the following single line of code would convert to any arbitrary format,

NSData *bitmapData = [output representationUsingType:NSJPEGFileType
properties:nil];

Tagged with:
preload preload preload