💾 Archived View for thrig.me › blog › 2024 › 02 › 06 › letterscore.pl captured on 2024-07-09 at 03:17:32.

View Raw

More Information

⬅️ Previous capture (2024-03-21)

-=-=-=-=-=-=-

#!/usr/bin/env perl
# letterscore - "score" letters by how many pixels they activate,
# depending on the font
use 5.36.0;
use Imager;

my $font_file = shift // die "Usage: letterscore font.ttf\n";

my $img  = Imager->new( xsize => 128, ysize => 128 ) or die Imager->errstr;
my $fg   = Imager::Color->new("#FFFFFF");
my $bg   = Imager::Color->new("#000000");
my $font = Imager::Font->new( file => $font_file, color => $fg, size => 64 );
my $xmax = $img->getwidth - 1;
my $ymax = $img->getheight - 1;

for my $ch ( grep { /[[:print:]]/ } map { chr } 0 .. 127 ) {
    $img->box(
        color  => $bg,
        xmin   => 0,
        ymin   => 0,
        xmax   => $xmax,
        ymax   => $ymax,
        filled => 1
    );
    $img->string(
        font => $font,
        x    => 32,
        y    => 64,
        aa   => 0,
        text => $ch
    );
    my $count = count_em($img);
    $ch = "' '" if $ch eq ' ';
    say join ' ', $count, $ch;
}
# maybe have a look-see at the image to ensure the letter is actually
# fully within the bounding box (or use a library that lets you get
# the bounding boxes and keep them within a suitably sized image, blah
# blah blah)
$img->write( file => 'letterscore.png' );

sub count_em($img) {
    my $count = 0;
    for my $yy ( 0 .. $ymax ) {
        for my $xx ( 0 .. $xmax ) {
            my $c = $img->getpixel( x => $xx, y => $yy );
            $count += ( $c->hsv )[2];
        }
    }
    return $count;
}