termcol: use Imager for generic PNG generation
authorMischa POSLAWSKY <perl@shiar.org>
Mon, 2 Nov 2015 05:14:51 +0000 (06:14 +0100)
committerMischa POSLAWSKY <perl@shiar.org>
Tue, 5 Jan 2016 00:05:07 +0000 (01:05 +0100)
Obviously less efficient than replacing palette at a hardcoded position,
but more flexible and reliable with different sources.

Still only loaded if requested.

termcol.plp

index 04157ef95798ed3fa47d0e5f4fbd668c11a70467..73bf0d2190d5f3132b8ecd3e1ff70cdc65cf7642 100644 (file)
@@ -14,7 +14,7 @@ Html({
        stylesheet => [qw'light dark'],
 });
 
-my $imgfile = exists $get{img} && 'indi.png';
+my $imgfile = $get{img} // exists $get{img} && 'indi.png';
 
 my @termlist;
 push @termlist, split /\W+/, $ENV{PATH_INFO} || 'default';
@@ -75,20 +75,16 @@ sub colcell {
 sub img_egapal {
        my ($palette) = @_;
        return eval {
+               require Imager;
                require MIME::Base64;
-               require Digest::CRC;
-
-               local $/;
-               open my $img, '<:bytes', "data/$imgfile" or die "$!\n";
-               my $imgdata = readline $img;
-
-               my $offset = 0x29 - 4;
-               my $len = 16 * 3;
-               my $chunklen = $len + 4;
-               substr($imgdata, $offset+4, $len) = pack 'H*', join '', @{$palette};
-               my ($p, $crc) = unpack "x${offset}a${chunklen}N", $imgdata;
-               substr($imgdata, $offset+4+$len, 4) = pack 'N', Digest::CRC::crc32($p);
 
+               my @imgpal = map { Imager::Color->new(ref $_ ? @$_ : $_) } @{$palette};
+               state $img = Imager->new(file => "data/$imgfile")
+                       or die Imager->errstr.$/;
+               @{[ $img->getcolors ]} == @imgpal
+                       or die "incompatible palette size\n";
+               $img->setcolors(colors => \@imgpal);
+               $img->write(data => \my $imgdata, type => 'png');
                return sprintf '<img src="data:image/png;base64,%s">',
                        MIME::Base64::encode_base64($imgdata);
        } || $@;