Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to resize an NSImage which turns into NSData

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.

like image 675
Ricky Avatar asked Dec 23 '22 04:12

Ricky


1 Answers

I found this blog post to be very helpful for resizing my image: http://weblog.scifihifi.com/2005/06/25/how-to-resize-an-nsimage/

You will need to enforce the aspect ratio on the image resizing yourself, it won't be done for you. This is how I did it when I was trying to fit the image into the printable area on the default paper:

NSImage *image = ... // get your image
NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
NSSize paperSize = printInfo.paperSize;
CGFloat usablePaperWidth = paperSize.width - printInfo.leftMargin - printInfo.rightMargin;
CGFloat resizeWidth = usablePaperWidth;
CGFloat resizeHeight = usablePaperWidth * (image.size.height / image.size.width);

Here is a slightly modified version of his code from the blog:

NSData *sourceData = [image TIFFRepresentation];
float resizeWidth = ... // your desired width;
float resizeHeight = ... // your desired height;

NSImage *sourceImage = [[NSImage alloc] initWithData: sourceData];
NSImage *resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(resizeWidth, resizeHeight)];

NSSize originalSize = [sourceImage size];

[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];

[sourceImage release];
[resizedImage release];
like image 67
Kenny Wyland Avatar answered Jan 04 '23 00:01

Kenny Wyland