[MacRuby-devel] A neat little discovery: MacRuby + ImageMagick

John Labovitz johnl at johnlabovitz.com
Mon Dec 17 11:16:12 PST 2012


I've been writing some personal tools for processing photographic images (film scans, if you must know). For most of it, I've been using Ruby 1.9 and the ImageMagick library, which has a very rich toolset of image-manipulation functions that are fairly easy to program using the RMagick gem that hooks up to the ImageMagick core engine. (Note: *not* running ImageMagick via sub-shells.)

However, these are all batch tools (run from the command line). When I needed a tool with a GUI, I used MacRuby, and then got very frustrated trying to get Cocoa to be as functional as ImageMagick. To start with, there's the confusing mess of NSImage vs. CGImage vs. CIImage, etc. I found that Cocoa's great for doing things it's good at, but once you start driving off the road, you run into boulders.

Anyway, this morning I realized I could glue the two together, simply by installing the RMagick gem in MacRuby! I always assumed that would break. But nope, it works fine. (I've installed ImageMagick using Homebrew, BTW.)

For example, here's my Cocoa-only code for loading an image from a file into a CIImage:

	ci_image = CIImage.imageWithContentsOfURL(NSURL.fileURLWithPath(path))

and here's the new code with ImageMagick/RMagick:

	im_image_list = Magick::Image.read(path)
	# do some ImageMagick magic here!
	im_image = im_image_list.first
	data = im_image.to_blob.to_data
	ci_image = CIImage.imageWithData(data)

Obviously, that's more code (though I've separated it to be a bit more readable). And it probably involves one or two copies of the image data, more than is needed. And doesn't lend itself to CIFilter-like realtime processing. But the point is that now I can process an image using ImageMagick, and display it using Cocoa, all in the same Ruby process!

--John

PS: This doesn't address packaging. These are my own tools, and so I'm just writing them as simple executables -- I'm not even building application bundles. Obviously if one was to ship an app using ImageMagick internally, there'd be some work to package it into the bundle.


More information about the MacRuby-devel mailing list