ImageCrop source code

A trivial piece of code, but one I often find myself in need of.

NSImage+MGCropExtensions is a category on NSImage which lets you obtain a version of the image scaled to a specified size (using high-quality interpolation), via a choice of four methods:

  • Crop (Center) – proportionally scale the image to fit the appropriate dimension of the target size, and then center-cropped to produce the required size.
  • Crop Start – as for Crop, but cropped at the “start” of the image, i.e. either the top or left, depending on the relative aspect-ratios of the source image and the target size.
  • Crop End – as for Crop Start, but using the “end” of the image, i.e. the bottom or right.
  • Scale to Fit – proportionally scale the image to fit entirely within the target size, leaving transparency around it if necessary.

If that sounds complicated, just download the source code and try out the included sample app; it’ll all make sense. Useful when you want to make an arbitrary image fit into an arbitrary region, either with or without space around the resulting image. You can also take a look at a screenshot, as usual. Find more code on my Cocoa Source Code page.

5 comments

  1. Thanks for sharing this. May I suggest that you include a copy of the license terms in each source code download, in addition to the centralized location on your web site? It was difficult for me to determine what the license was since your sources files just claim all rights reserved and make no mention of a license grant.

  2. [...] Matt Gemmell shares a category on NSImage with some useful cropping utilities. It’s nice to see example/public code at this level of refinement. Should save some of you a half or full day of work. Although the license is not obvious or included in the download, it is listed on this page and is a fairly standard attribution license. Link. [...]

  3. Hey Daniel,

    Yep, that’s definitely something I should be doing; occurred to me yet again last night once the computer was asleep. I’ll try to get around to updating the existing archives soon, and I’ll always include the license with new stuff from now on.

    Any existing mention of rights in the source is just Xcode boilerplate; I guess I should change that template too, to save some time.

    Cheers,
    -M

  4. Very nice, it’s made a project I am working on _much_ simpler. ;)

    One note: this code doesn’t handle high-dpi images very well, it seems to take a low-resolution sample of it and scale _that,_ instead of using all the image data. As a result a 720-dpi image scaled full screen looks blocky and jagged, whereas the same image converted to 72-dpi is perfectly smooth.

  5. This has saved me hours of coding! Thank you dearly.

    Ricky.

Leave a comment