views:

316

answers:

2

I have an NSImage which I am trying to resize like so;

NSImage *capturePreviewFill = [[NSImage alloc] initWithData:previewData];
NSSize newSize;
newSize.height = 160;
newSize.width = 120;
[capturePreviewFill setScalesWhenResized:YES];
[capturePreviewFill setSize:newSize];

NSData *resizedPreviewData = [capturePreviewFill TIFFRepresentation]; 
resizedCaptureImageBitmapRep = [[NSBitmapImageRep alloc] initWithData:resizedPreviewData];
saveData = [resizedCaptureImageBitmapRep representationUsingType:NSJPEGFileType properties:nil];
[saveData writeToFile:@"/Users/ricky/Desktop/Photo.jpg" atomically:YES];

My first issue is that my image gets squashed when I try to resize it and don't conform to the aspect ratio. I read that using -setScalesWhenResized would resolve this problem but it didn't.

My second issue is that when I try to write the image to a file, the image isn't actually resized at all.

Thanks in advance, Ricky.

A: 

If you can require Mac OS X 10.6 or later, send your image a CGImageForProposedRect:context:hints: message, then write the CGImage out using a CGImageDestination object.

The rectangle should have NSZeroPoint as its origin, and its size be the size you want.

This still won't scale the image proportionally (maintaining aspect ratio); you have to do that yourself.

Peter Hosey
I haven't really done any work with CG before. If it's not going to scale the image proportionally, then why am I using it? It seems the same as NSImage's -setSize
Ricky
You're using it (or the other solution) to scale the image. Doing so *proportionally* is up to you. There is no Cocoa-provided way to scale an image proportionally, except in display only (in an image view).
Peter Hosey
A: 

The pre-10.6 way to do this (without going through a TIFF representation) is to lock focus on the resized image, create an NSBitmapImageRep for the extent of the image (that is, a rectangle with zero origin and the image's size), unlock focus, and then ask that bitmap image rep for JPEG data.

Peter Hosey