Python-MagickWand or How to Work With Icons

Published June 18th, 2009, updated March 17th, 2013.

I’m currently working on a pet project where I want to convert favicons (in Windows .ico format) to Web standard .png format. I started using the Python Image Library (PIL) for this, which supports plenty of image formats and which is Python’s standard way for doing image manipulations. A basic any_to_png function using PIL looks like this:

img = Image.open(StringIO(buf))
img = img.resize((16,16),Image.ANTIALIAS)
img.save(buf, format='PNG', transparcency=1 )
return buf.getvalue()

This is straight forward, but I had to find out that PIL’s .ico support is pretty outdated while Microsoft has updated the specs. Modern .ico files have switched from .bmp to .png format and added alpha masks. There is a patch available that brings you .png support, but alpha masks are still broken.

So, I’ve searched for another image library that has proper support for icon files and stumpled upon my old friend ImageMagick. I’ve found that there are Python bindings for the MagickWand interface (the C API). Yet, those bindings are incomplete, ugly and not actively maintained. I’ve found alternate Python bindings for the MagickWand interface and those are pretty nice:

img = Image(StringIO(buf), 'ico')
if not i.select((16,16)):
    i.alpha(True)
    i.scale((16,16))
return i.dump('png')

You see, Ian Stevens‘ CDLL bindings are a straight forward implementation of the MagickWand C API using the CDLL wrapper library. I’ve added some missing functions, documentation and clarified the licensing issues (now available under a BSD license) and I think this is a clean and elegant solution for a long standing problem. You can find a snapshot of Python MagickWand here and the latest source code there. Enjoy.

visit github repository
visit original project page

2009-12-08: We’ve cloned python-magickwand and accept patches. You can find our latest work in our mercurial repository. Today, we’ve commited a magickwand6.5 patch, please look at the hg changelog for details.

2010-03-30: There’s an updatedrefactored package around by Oliver Berger, see pypi. I’ve not yet looked into the changes (aside of a modified copyright statement), but I’ll merge it into our repository soon. If you fork the codebase, please drop a line; I’d like to have a common repository where we can focus our efforts.

2010-05-20: I’ve checked Oliver’s code, aside of refactoring there are no functional changes. There’s also no update form Ian (who is the original author), so our version here is still the recommended release. Feel free to send patches and bug reports.

2011-09-19: I’ve added some minor updates and moved the source code to Github, see https://github.com/cxcv/python-magickwand.