views:

25

answers:

1

I have this code in a cocoa application to resize a PNG file to a certain dimension but I want the format to be still a PNG, but there is no PNGRepresentation method for NSImage. How do I do this?

NSData *sourceData = [NSData dataWithContentsOfFile:fileName];

NSImage *sourceImage = [[NSImage alloc] initWithData: sourceData];

NSSize originalSize = [sourceImage size];
float resizeWidth = originalSize.width - 10;
float resizeHeight = originalSize.height - 10;
NSImage *resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(resizeWidth, resizeHeight)];

[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, resizeWidth, resizeHeight) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];

NSData *resizedData = [resizedImage TIFFRepresentation];
[resizedData writeToFile:@"~/playground/resized.tif" atomically:YES];
[sourceImage release];
[resizedImage release]; 
A: 

You need a bitmap image rep to ask for its PNG representation.

While you have focus locked on the resized image, create and init a bitmap image rep with the focused “view”, passing the bounds of the image (origin NSZeroPoint, size of the rectangle = size of the image). Then ask that rep for its representation as a PNG file.

Note that you will lose properties such DPI, gamma, color profile, etc. If you want to preserve those, you'll need to use Core Graphics to do the whole job, from reading the file (with CGImageSource) through resizing the image (with CGBitmapContext) to writing the new file (with CGImageDestination).

Peter Hosey