Satya's blog - Image to CSS

Mar 19 2005 22:16 Image to CSS
After seeing bluesmoon's attempt at rendering an image as text, I remembered something about rendering an image with CSS -- not ASCII art like bluesmoon, premshree, et al, but a real image. And in perl, because let's face it I'm a perl weenie. After struggling a couple of hours, I came up with this:
use GD;

my $img = GD::Image->newFromJpeg($ARGV[0]);
my($w,$h) = $img->getBounds();
my($index,$r,$g,$b,$pixel,$prevpixel,$count);

print STDERR "height=$h width=$w\n";

print<<HTML;
<html> <head> <style>
.image td { width: 1px; height: 1px; }
</style> </head> <body>
<div class="image">
<table cellspacing="0" cellpadding="0">
HTML

for(my $y=0; $y<$h; $y++) {
    print "<tr>";
    $prevpixel='';
    for(my $x=0; $x<$w; $x++) {
        $index=$img->getPixel($x,$y);
        ($r,$g,$b)=$img->rgb($index);
        $pixel=sprintf("%02x%02x%02x",$r,$g,$b);
        if($prevpixel ne $pixel) {
            if($prevpixel ne '') {
                if($count>1) {
                    print ";width=$count\" colspan=\"$count";
                }
                print '"/>';
            }
            print "<td style=\"background-color: \#$pixel";
            $count=1;
            $prevpixel=$pixel
        }
        else {
            $count++;
        }
    }
    if($count>1) {
        print ";width=$count\" colspan=\"$count";
    }
    print '"/>';
    print "</tr>\n";
}

print<<HTML;
</table> </div> </body> </html>
HTML

(sorry, LJ users, no cut tags here) which on my 2425 byte test image

(test image)

produced this page which weighs in at 353591 bytes (17533 bytes gzipped). That makes this whole exercise an academic because-I-can thing. That's why there's no use strict; and use warnings; and why I use $ARGV[0] directly.

Last updated: Mar 19 2005 22:43