====== GD Libary - Programmbibliothek für die Bearbeitung von Grafiken ======
Mit der GD Libary ist es möglich, Grafiken in PHP zu erzeugen oder zu ändern. Voraussetzung ist, dass die Programm-Bibliothek auf dem Server installiert ist.
Mit der folgenden PHP-Funktion ist es möglich, einen Text zu einer bestehenden Grafik hinzuzufügen:
function addTextToImage( $text, $image_out )
{
// ***** BEGIN CONFIGURATION ***** //
// original image
$filename = "template.gif";
$width = 150;
$height = 150;
// text position
$left = -1; // -1 for horizontal center
$top = 50; // -1 for vertical center
// text font
$ttf = 'arial.ttf';
$size = 18;
$angle = 0;
// text color
$red = 255; // from 0 (black) to 255 (white)
$green = 255; // from 0 (black) to 255 (white)
$blue = 255; // from 0 (black) to 255 (white)
// ***** END CONFIGURATION ***** //
if( file_exists( $filename)) {
$functions = [".gif" => ["imagecreatefromgif", "imagegif"],
".jpg" => ["imagecreatefromjpeg", "imagejpeg"],
".jpeg" => ["imagecreatefromjpeg", "imagejpeg"],
".png" => ["imagecreatefrompng", "imagepng"]
];
$pos = strrpos( $filename, "." );
$ext = strtolower( substr( $filename, $pos ) );
$func = $functions[$ext][0]; // get functionname
$im = $func( $filename ); // function imagecreate...
$col = ImageColorAllocate( $im, $red, $green, $blue ); // create color
if( $left == -1 | $top == -1 ) { // horizontal or vertical center
$box = imagettfbbox( $size, $angle, $ttf, $text ); // get box from text
if( $left == -1 ) { // horizontal center
$text_width = abs( $box[4] - $box[0] ); // top-right - bottom-left
$left = round( ($width - $text_width ) / 2 ); // new value for left
}
if( $top == -1 ) { // vertical center
$text_height = abs($box[5] - $box[1]);
$top = round( ($height - $text_height) / 2 ) + $text_height; // new value for top
}
}
Imagettftext( $im, $size, $angle, $left, $top, $col, $ttf, $text );
$func = $functions[$ext][1]; // get functionname
$func( $im, $image_out ); // function imagecreate...
}
else
echo "file not exist!";
}
**Aufruf-Beispiel:**
addTextToImage( "PHP ist toll", "new.gif" );