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.
Comments (8)
Christof on May 18, 2008:
# line 31
out = open(filename, "wb")
I also get a DeprecationWarning: struct integer overflow
masking is deprecated
out.write(struct.pack("!I", checksum))
Any other way to do it?
But a very useful script, thanks!
James Tauber on May 18, 2008:
Rich LaMarche on May 18, 2008:
Jim Dabell on May 18, 2008:
You can see the SVG equivalent of your example here:
http://pastebin.com/f59ef3ff8
There are a few advantages to doing it this way. It allows for more complex images than simple gradients. You can start an idea off in a graphics application like Inkscape and have it generate SVG as a starting point. You can use template languages like Genshi to generate images. You have the option of serving the SVG directly for some clients.
Rene Dudfield on May 19, 2008:
here's an example of doing that stuff in pygame... with a few more different types of gradients:
http://www.pygame.org/project/307/
cheers,
Scott Johnson on May 19, 2008:
I think the major win with this code is that it doesn't need any non-standard libraries.
As for the DeprecationWarning, the following code will suppress it:
import warnings
warnings.simplefilter("ignore",DeprecationWarning)
Scott Johnson on May 19, 2008:
http://pastie.textmate.org/199703
Add a Comment
Last Modified: May 18, 2008
Author: jtauber
Empty on May 18, 2008: