In my last post I was looking for a way to give simple images transparent backgrounds. I noted that PHP GD’s imagefill function wasn’t quite what I was looking for as it only replaced exact colours based on your starting image coordinates. I gave this problem some brief thought and came up with a slightly better algorithm using colour distance calculation and simple recursion.
First of all, what’s better is the result (well, for my purposes at least). See below:
It’s slower. Much, much, much slower. The built-in imagefill function took approximately 0.0007 seconds. My algorithm took 2.485 seconds. This is pretty much unacceptable. This sort of programming isn’t my forte, so I don’t know if I should attribute this to my algorithm itself (which I whipped up rather quickly without much thought), or if it’s because the PHP GD library is a built-in, compiled C library and mine is simple uncompiled PHP.
Secondly, it kept crashing my Apache (XAMPP 1.7.3, PHP 5.3.1, Apache 2.2.14). It worked great as a command line script and output my new image beautifully. It might/probably will crash your Apache, so use caution. It shouldn’t need to be said, but don’t try this on your production boxes.
Thirdly, with large images, it will probably eat up loads of memory or seg fault. I had to adjust my xdebug.max_nesting_level configuration variable to get this working properly (value to something huge like 50,000).
Like my Transparentizer class/algorithm, it could definitely use some sort of anti-aliasing, but that’s a whole other beast.