#!/usr/bin/perl use GD; use CGI; use constant font_directories => ; use constant default_font => 'Junkyard'; use constant default_size => 50; use constant default_text => 'font->png test'; use constant default_wrap => 0; use constant default_fore => qw(0 0 0); # black use constant default_back => undef; # transparent use constant default_over => 0; # don't overflow large words for text wrap my $q = new CGI; my $size = $q->url_param('size') || default_size; my $text = $q->url_param('text') || default_text; my $wrap = $q->url_param('wrap') || default_wrap; my $over = $q->url_param('over') || default_over; # TODO: support named colors with GD::Simple my @fg = default_fore; if ($q->url_param('fgcolor') =~ m/^(?:0x)([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})$/i) { @fg = map { hex } ($1, $2, $3); } my @bg = default_back; if ($q->url_param('bgcolor') =~ m/^(?:0x)([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})$/i) { @bg = map { hex } ($1, $2, $3); } # TODO: support GD::Image->useFontConfig for finding fonts font: for $font ($q->url_param('font'), default_font) { for $dir (font_directories) { warn "checking $dir/$font*"; if ((@matches = <$dir/$font*>) && -f $matches[0]) { $fontfile = $matches[0]; last font; } warn "nope"; } } die unless -r $fontfile; die unless $size > 0; die unless $text; if ($wrap > 0) { use Text::Wrap qw(wrap $columns $huge); $columns = $wrap + 1; $huge = $over ? 'overflow' : 'wrap'; $text = wrap('', '', $text); } my @bounds = GD::Image->stringFT(0, $fontfile, $size, 0,0,0, $text) or die "$! $fontfile"; my ($width, $height) = ($bounds[2] - $bounds[6], $bounds[3] - $bounds[7]); my ($x, $y) = map {-$_} @bounds[6,7]; my $im = new GD::Image($width, $height) or die; if (@bg == 3) { $bg = $im->colorAllocate(@bg); } else { @bg = map { abs(255 - $_) } @fg; # this color isn't actually used, just set to transparent $im->transparent($im->colorAllocate(@bg)); # N.B. transparent color must be first color allocated; this is not documented! } $fg = $im->colorAllocate(@fg); $im->stringFT($fg, $fontfile, $size, 0, $x, $y, $text); print "Content-Type: image/png\n\n"; print $im->png or die;