Here are some code to create a square thumbnail in Quartz and Objective-C
#include <CoreServices/CoreServices.h>
#include <Quartz/Quartz.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString * sourcePath = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding];
NSString * destPath = [NSString stringWithCString:argv[2] encoding:NSUTF8StringEncoding];
int desiredWidth = 128;
int desiredHeight = 128;
// determined the size of image to scale
NSImage * image = [[NSImage alloc] initWithContentsOfFile:sourcePath];
NSSize targetSize = NSMakeSize(desiredWidth, desiredHeight);
NSSize originalSize = [image size];
float originalWidth = originalSize.width;
float originalHeight = originalSize.height;
float targetWidth = targetSize.width;
float targetHeight = targetSize.height;
float scaleFactor = 1.0;
if(originalWidth > originalHeight)
{
scaleFactor = targetHeight / originalHeight;
}
else
{
scaleFactor = targetWidth / originalWidth;
}
float scaledWidth = originalWidth * scaleFactor;
float scaledHeight = originalHeight * scaleFactor;
targetSize = NSMakeSize(scaledWidth, scaledHeight);
// resize image
NSPoint thumbnailPoint = NSZeroPoint;
NSImage* newImage = [[NSImage alloc] initWithSize:targetSize];
[newImage lockFocus];
NSRect thumbnailRect;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = targetSize.width;
thumbnailRect.size.height = targetSize.height;
[image drawInRect: thumbnailRect
fromRect: NSZeroRect
operation: NSCompositeSourceOver
fraction: 1.0];
[newImage unlockFocus];
NSSize sx = NSMakeSize(desiredWidth, desiredHeight);
float width = 0;
if(targetSize.width > targetSize.height)
{
thumbnailPoint.x = (targetSize.width - targetSize.height) / 2;
width = targetSize.height;
}
else
{
thumbnailPoint.y = (targetSize.height - targetSize.width) / 2;
width = targetSize.width;
}
// create square thumbnail
NSImage *newImage2 = [[NSImage alloc] initWithSize:sx];
[newImage2 lockFocus];
NSRect drawInRect;
drawInRect.origin = NSZeroPoint;
drawInRect.size.width = width;
drawInRect.size.height = width;
NSRect fromRect;
fromRect.origin = thumbnailPoint;
fromRect.size.width = width;
fromRect.size.height = width;
[newImage drawInRect: drawInRect
fromRect: fromRect
operation: NSCompositeSourceOver
fraction: 1.0];
[newImage2 unlockFocus];
// Save the image
NSData *imageData = [newImage2 TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData: imageData];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] forKey:NSImageCompressionFactor];
NSData *data = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];
[data writeToFile: destPath atomically:YES];
[pool release];
NSLog(@"Done");
return 0;
}
Comments