#!/usr/bin/perl
use strict;
use warnings;
use CGI::Carp qw/fatalsToBrowser/;
use CGI;
use Time::HiRes qw(tv_interval gettimeofday);
my $t0 = [gettimeofday];
use GD;
my $q = new CGI;
#print $q->header;
print $q->header("image/png");
my $img = GD::Image->new(1000,400, 1);
my $white = $img->colorAllocate(255,255,255); # first allocation defines background color
my $black = $img->colorAllocate(0,0,0);
my $pink = $img->colorAllocate(228,32,216);
my $text = $q->param("text") || "Hallo Welt, wie gehts?";
my $font = "./Fonts/verdana.ttf";
my $maxwidth = $q->param("x") || 312;
my $maxheight = $q->param("y") || 30;
my ($points,@bounds) = stringIntoBox($text, $font, $maxwidth, $maxheight, 5);
my $boxWidth = $bounds[2] - $bounds[0];
my $boxHeight = $bounds[1] - $bounds[7];
my @rectCoords = (10, 10, $maxwidth + 10, $maxheight + 10);
# Rendering the font
$img->stringFT($white,$font,$points, 0, 10-$bounds[0], 10+$boxHeight-$bounds[1], $text );
# Draw the Bounding Box
$img->rectangle(@rectCoords, $pink);
# Informational stuff
my $infoyoffset = 305;
$img->string(gdMediumBoldFont, 2, $infoyoffset, "Bounding Box:", $white);
$img->string(gdMediumBoldFont, 20, $infoyoffset + 15, "Links Oben: [ $bounds[6],$bounds[7] ]", $white);
$img->string(gdMediumBoldFont, 20, $infoyoffset + 30, "Links Unten: [ $bounds[0],$bounds[1] ]", $white);
$img->string(gdMediumBoldFont, 20, $infoyoffset + 45, "Rechts Oben: [ $bounds[4], $bounds[5] ]", $white);
$img->string(gdMediumBoldFont, 20, $infoyoffset + 60, "Rechts Unten: [ $bounds[2], $bounds[3] ]", $white);
$img->string(gdMediumBoldFont, 2, $infoyoffset + 80, "Maximale Schriftgroesse: $points pt", $white);
$img->string(gdMediumBoldFont, 820, 385, "Rendering took " . tv_interval($t0)*1000 . "ms", $white);
print $img->png;
sub stringIntoBox {
my $string = shift;
my $font = shift;
my $width = shift;
my $height = shift;
my $startpoints = shift || 0.5;
my $dummyimg = GD::Image->new(1,1);
my $black = $dummyimg->colorAllocate(0,0,0);
my (@bounds, $calcwidth, $calcheight, $lastpoints);
do {
$lastpoints = $startpoints;
$startpoints += 0.5;
@bounds = GD::Image->stringFT(
$black,
$font,
$startpoints,
0,
0,
0,
$string
);
$calcwidth = $bounds[2] - $bounds[0];
$calcheight = $bounds[1] - $bounds[7];
#print $calcheight, "<br/>";
} while( $calcwidth < $width && $calcheight < $height );
return ($lastpoints, @bounds);
}
|