
418
|
Chapter 7, Names and Places
#83 Map Numerical Data the Easy Way
HACK
Note that hacking the GIF palette works for mapping
countries of the world or, say, states of the U.S., because
there are fewer than 256 of each. If you were interested in
mapping voter turnout across San Francisco’s more than 400
voting precincts, you’d need to use a different technique,
such as the one described in “Plot Statistics Against Shapes”
[Hack #44].
Hacking the GIF Palette
Let’s work our way up from a simple example. Say we want to convert a
color GIF into grayscale. Using Python and some image library, this can per-
haps be done more elegantly, but if we don’t care too much about image
size, the following little script will do. If we assume that
f is a file-like object
containing a GIF and
o is a file-like object able to receive a GIF, then this bit
of Python will recolor the image in grayscale and dump it to
o:
1 header = f.read(13)
2 o.write( header )
3 for i in range(1 << ( (ord(header[10]) & 7) +1 )):
4 gray = (ord(f.read(1)) + ord(f.read(1)) + ord(f.read(1)))/3
5 o.write(3*chr(gray))
6 o.write( f.read( ) )
Not bad for six lines of code! In the third line, we calculate the size of the
palette by left-shifting the lowest 4 bits of the tenth byte of the header. Then
we loop through the palette and average each RGB triple and write that to
the output. We finish by writing what’s left in the buffer back to the output. ...