.comment-link {margin-left:.6em;} <$BlogRSDURL$>

Monday, April 25, 2005

Getting Geeky 

I haven't gotten all geeky for a while. At work I'm dealing with a database that stores TIFF files for later use. But what usually happens is that the TIFF file is converted to a JPEG and the JPEG (or portions thereof) are displayed on a web browser. The first version of the database used the file system extensively for saving the TIFF and JPEG files as well as squirreling away other things that IMHO should be stored the database. This is all well and good but if you can't get the images back out of the database and manipulate them, then all you have is write-only memory which is no good to man or beast. Being the Python guy that I am I want to do as much as possible in that most superior language. The first step was getting the TIFFs into the database, that was pretty easy. Getting them back out and displayed was only slightly more difficult. But I've been pounding my head against the wall trying to get PIL to compile. I finally did that and then had to get it to work the database; more head banging. Here's the situation: let's say you have a table called pic that stores a TIFF file in a longblob called tiff (Oh yeah, this is all being done in MySQL), you have a connection to your database called db (a wrapper around MySQLdb.py) and you have the Image module loaded. Here is an example of Python debugging:

buff = db.query("select tiff from pic where id = %d" % pictureId)[0][0]
image = Image.open(StringIO.StringIO(buff))

Chokes and dies with a IOError: cannot identify image file exception. No matter how many times you try it, even if you try explicitly setting the mode to "RGB" it throws the exception. If you read a copy of the image from the file system into ram and put it into a StringIO instance it works fine. But then the epiphany: MySQLdb returns blobs as array instances, not strings! Aha! How about:

buff = db.query("select tiff from pic where id = %d" % pictureId)[0][0].tostring()
image = Image.open(StringIO.StringIO(buff))

That works like a charm. No exception thrown and if you call image.show() you see the picture! Woo!

This is another instance demonstrating Hank's Axiom. What is Hank's Axiom you ask? Why nothing could be simpler, internets. Hank's Axiom: All bugs are small Or to put it another way, really big errors in your program are not bugs, they show your fundamental misunderstanding of the problem. A bug, OTOH, is some finicky little thing that, when you find it, makes you crazy because it is so trivial and lame you should have seen it half an hour ago.


Comments: Post a Comment


This page is powered by Blogger. Isn't yours?