Over the course of the past year I've become a huge fan of Apple's Mac OS X on the server-side. Learning about and taking advantage of some cocoa programming fu, like CoreImage.
Of course, I'm primarily a PHP programmer, not that I couldn’t hack around in cocoa, I just haven't had much time to learn more about it.
Luckily, I don't necessarily have to learn cocoa to experiment with CoreImage on the server-side today. Thanks to Mark Liyanage's CoreImageTool shell application.
Mark's tool gives you the power to use CoreImage from the command line, and therefore from just about any scripting language that Mac OS X supports such as PHP, Perl, Python, and so on.
I've used this application to create a nifty thumbnail generator for my web-based Finder clone. Since it's powered by CoreImage, it supports a variety of image formats, allowing me to transform psd, ai, eps… and many others on the fly to web-supported image formats like png, jpg, or gif.
Writing the tool was surprisingly easy. To keep my PHP portable, I put in a check for Darwin, if it was present, I look for whether CoreImage Tool is installed. If it isn't, I fallback on PHP's GD extension, which unfortunately limits me to a much smaller pool of formats. In the future I should swap out GD support for ImageMagick.
Following is what the CoreImage portion looks like:
The preceding example is pretty simple, and yet fairly powerful as well. CoreImage can only resize an image via the specification of a scaling factor. In my example, I only allow the image to be scaled down, not scaled up, since this code is intended for creating smaller images, like thumbnails, from high-res source content.
To make things easier, I use the Darwin sips command to get the source image's dimensions in pixels, then I take the new thumbnail width and I divide that by the original width to get the scaling factor. For the destination, I have to specify an Apple Universal Type Identifier. I'm certain that part could be automated, rather than hard coded, like I've done. In the future I'll expand this script to automatically query that information. The UTI is Apple's own concept of a file type, and can be thought to be similar to mime types and extensions, but true to Apple style, is done in a much cleaner, more extensible way.
Mark mentions that his tool is written for Mac OS 10.4, Tiger, but I've been using it on 10.5 Leopard client and server without any problems.
That said, the preceding code is a small snippet of a much larger system that I designed that takes high quality source PSD files and converts and resizes them into web-accessible formats like PNG, JPG, and GIF, on the fly. And it's super fast to boot.