Re: Resizing an NSImage (and getting good-looking results!)
Re: Resizing an NSImage (and getting good-looking results!)
- Subject: Re: Resizing an NSImage (and getting good-looking results!)
- From: glenn andreas <email@hidden>
- Date: Tue, 25 Jan 2005 12:20:27 -0600
On Jan 25, 2005, at 9:31 AM, Toby Atkin-Wright wrote:
I want to load a JPEG, reduce it in size, and convert the new image to
a JPEG ready for upload to a web site. The following code works, but
the results look unpleasantly rough:
// load and prepare image
NSImage* theImage = [[NSImage alloc]
initWithContentsOfFile:theFilename];
[theImage setScalesWhenResized:YES];
// resize the image
[theImage lockFocus];
[[NSGraphicsContext currentContext]
setImageInterpolation:NSImageInterpolationHigh]; // does this do
anything?
[theImage setSize:theNewSize]; // theNewSize is an NSSize struct
[theImage unlockFocus];
// convert it back to a JPEG
NSData* theImageDataTemp = [theImage TIFFRepresentation];
NSBitmapImageRep* theImageRepresentation = [NSBitmapImageRep
imageRepWithData:theImageDataTemp];
NSDictionary* theProperties = [NSDictionary
dictionaryWithObject:[NSNumber numberWithFloat:0.9]
forKey:NSImageCompressionFactor];
NSData* theImageData = [theImageRepresentation
representationUsingType:NSJPEGFileType properties:theProperties];
I guess its not doing any anti-aliasing when resizing the image. I was
hoping that calling setImageInterpolation:NSImageInterpolationHigh on
the graphics context would help, but it doesn't seem to make any
difference.
What should I be doing?
To get the image resized & resampled, doing a simple setSize of
theImage isn't going to do the trick - you'll need to explicitly redraw
& resample it at the new size yourself.
I've gotten good results with code like this:
// resize the image
NSImage *resizedImage = [[NSImage alloc] initWithSize: theNewSize];
[resizedImage lockFocus];
[NSGraphicsContext saveGraphicsState];
[[NSGraphicsContext currentContext]
setImageInterpolation:NSImageInterpolationHigh];
[image drawInRect:NSMakeRect(0.0,0.0,theNewSize.width,
theNewSize.height) fromRect:NSMakeRect(0.0,0.0,[image size].width,
[image size].height) operation:NSCompositeCopy fraction:1.0];
[NSGraphicsContext restoreGraphicsState];
[resizedImage unlockFocus];
(and then you grab the data from the resized image, and don't forget to
release it when done)
Glenn Andreas email@hidden
<http://www.gandreas.com/> oh my!
Mad, Bad, and Dangerous to Know
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden