Scaling, padding, Cocoa, and Bindings

I mentioned a while ago needing to implement batched image processing for my mom’s website that would allow her to easily generate a bunch of images of a certain size, padded with a certain color, for her website.

Besides the problems I mentioned in that post, I soon discovered that wrapping things up for Automator isn’t as easy as it ought to be, because Cocoa automator components only support a couple of data types, none of them the ones I needed to handily read in image files, pass them through Quartz Composer compositions, and then write the results back to the file system. I even had a helpful post from an Apple employee on one of the mailing lists, but in the end decided it would be simpler and I’d get better performance out of the result by just writing a custom application.

I pulled my copy of “Cocoa Programming for Mac OS X”, a book by Aaron Hillegas that I recommend for anyone wanting to learn general Cocoa programming. Then I dove right in to Interface Builder to design the interface and help me flesh out the functional spec. It was pretty easy to do that part, and I ended up with a short list of things I needed to do:

  • Bind user interface elements to user defaults, including non-string things like NSColor
  • Verify desired image sizes are valid
  • Choose directories for input files and output files with a file browser
  • Verify the input files are valid image files that can be read by Quartz
  • Load the image files
  • Scale them to a certain size, preserving their aspect ratio
  • Pad them to be square
  • Save them back to disk
  • Display a modal sheet with a progress panel, also using bindings

I learned a lot doing this project: I experimented with several of the graphics APIs, including Core Graphics, Core Image, and NSImage; I used bindings for something other than a spiffy but meaninglessly simple IB demo; and I handled the user interface nicities often not handled by example code. Did I mention this app is also fast? I’ve also accomplished the same task with Graphic Converter that I’m solving here with my own app, and mine is much faster at generating thumbnails.

If you’re interested, you can download the pre-built application or visit my subversion repository for the source code, which I’ve put under a BSD license.

I’ve really enjoyed the graphics programming, and will probably pick up Quartz 2D Graphics for Mac OS X(R) Developers and Programming with Quartz.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.