How to make a perfect crop (without changing the quality) in Objective-c/Cocoa (OSX) How to make a perfect crop (without changing the quality) in Objective-c/Cocoa (OSX) objective-c objective-c

How to make a perfect crop (without changing the quality) in Objective-c/Cocoa (OSX)


use CGImageCreateWithImageInRect.

// this chunk of code loads a jpeg image into a cgimage// creates a second crop of the original image with CGImageCreateWithImageInRect// writes the new cropped image to the desktop// ensure that the xy origin of the CGRectMake call is smaller than the width or height of the original imageNSURL *originalImage = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"lockwood" ofType:@"jpg"]];CGImageRef imageRef = NULL;CGImageSourceRef loadRef = CGImageSourceCreateWithURL((CFURLRef)originalImage, NULL);if (loadRef != NULL){    imageRef = CGImageSourceCreateImageAtIndex(loadRef, 0, NULL);    CFRelease(loadRef); // Release CGImageSource reference}    CGImageRef croppedImage = CGImageCreateWithImageInRect(imageRef, CGRectMake(200., 200., 100., 100.));CFURLRef saveUrl = (CFURLRef)[NSURL fileURLWithPath:[@"~/Desktop/lockwood-crop.jpg" stringByExpandingTildeInPath]];CGImageDestinationRef destination = CGImageDestinationCreateWithURL(saveUrl, kUTTypeJPEG, 1, NULL);CGImageDestinationAddImage(destination, croppedImage, nil);if (!CGImageDestinationFinalize(destination)) {    NSLog(@"Failed to write image to %@", saveUrl);}CFRelease(destination);CFRelease(imageRef);CFRelease(croppedImage);

I also made a gist:

https://gist.github.com/4259594


Try to change the drawInRect orign to 0.5,0.5. Otherwise Quartz will distribute each pixel color to the adjacent 4 fixels.

Set the color space of the target image. You might be having a different colorspace causing to to look slightly different.

Try the various rendering intents and see which gets the best result, perceptual versus relative colorimetric etc. There are 4 options I think.

You mention that the colors get modified by the saving of JPEG versus PNG.

You can specify the compression level when saving to JPEG. Try with something like 0.8 or 0.9. you can also save JPEG without compression with 1.0, but ther PNG has a distinct advantage. You specify the compression level in the options dictionary for CGImageDesinationAddImage.

Finally - if nothing her helps - you should open a TSI with DTS, they can certainly provide you with the guidance you seek.


The usual problem is that cropping sizes are float, but image pixels are integer.cocoa interpolates it automatically.

You need to floor, round or ceil the size and coordinates to be sure that they are integer.

This may help.