The Achilles Heel of DTR

Saturday, October 15th, 2005

When building this site, I wanted to use a custom font for all the headings, and after reading the tutorial on Dynamic Text Replacement at A List Apart, I decided to try it. Following my common philosophy of never using someone else’s code when I can write my own, I created a custom DTR script. The main difference between mine and the one on A List Apart is that I wanted to output transparent PNGs. Unfortunately, it turns out that the GD library in PHP is incapable of generating transparent text when any characters in a font overlap. You can see this problem in action in this image, where the end of the u is covered up by the x.

Picture of text

After digging through the bug reporting system for PHP, I ran across one in which a guy wanted to output alpha anti-aliased lines to transparent PNGs, but was unable to because, for “historical reasons”, GD cannot blend images this way (the bug). One more classic example of not treating transparency as just another channel I suppose.

So in order to output text that will be alpha blended, you have to run imagealphablending($img, false) so that all drawing to a pixel overwrites the existing contents of it without trying to blend the drawn color with its current color. So since imagettftext() and imagefttext() draw each character separately, if they overlap at all, they will overwrite the previous character.

So until GD is changed to use a different blending model, outputting transparent text is impossible. I thought of reporting this as a bug, but it seems that this is how the php and gd developers want it to behave. Of course IE’s complete inability to render transparent PNGs means that there really isn’t much point anyway 🙁