Creating Gradients Programmatically in Python


For various sites I often want to create a narrow gradient image. This site has two, for example, the grey background gradient and the purple header gradient.

Rather than having to open up a drawing tool every time I want to create one of these, I thought I'd write a Python script to generate a PNG of a gradient according to declarative specifications.

The result is

http://jtauber.com/2008/05/gradient.py

Only linear gradients are currently supported although you can have any number of them at different vertical offsets and it's easy to modify the code to support other gradient functions.

The code itself is 50 lines long and has no dependencies other than the standard library. I've included some samples based on the gradients on jtauber.com and Pinax.

For example, this gradient:

is produced with the following code:

write_png("test2.png", 50, 90, gradient([ (0.43, (0xBF, 0x94, 0xC0), (0x4C, 0x26, 0x4C)), # top (0.85, (0x4C, 0x26, 0x4C), (0x27, 0x13, 0x27)), # bottom (1.0, (0x66, 0x66, 0x66), (0xFF, 0xFF, 0xFF)), # shadow ]))

The 30-line write_png function could also be used more generally for generating any RGB PNGs.

The original post was in the categories: python web_design but I'm still in the process of migrating categories over.

The original post had 11 comments I'm in the process of migrating over.