Menu Home

PHP: 动态生成图片

dynamicImage.php

//把字体文件放在项目目录下
putenv("GDFONTPATH=" . realpath('.'));
$font = "AnkeCalligraph.ttf";
$size = isset($_GET['size']) ? $_GET['size'] : 20;
$text = isset($_GET['text']) ? $_GET['text'] : "";

//把2.png放入项目目录下
$image = imagecreatefrompng("2.png");
if(!$image) {
    $image = imagecreatetruecolor(150, 150);
    $bgc = imagecolorallocate($image, 255, 255, 255);
    $tc = imagecolorallocate($image, 0, 0, 0);
    imagefilledrectangle($image, 0, 0, 150, 30, $bgc);
    imagestring($image, 1, 5, 5, "Error loading", $tc);
}
$red = imagecolorallocate($image, 0xFF, 0, 0);
if($text) {
    //文字绘制在图片中心
    $tsize = imagettfbbox($size, 0, $font, $text);
    $dx = abs($tsize[2] - $tsize[0]);
    $dy = abs($tsize[5] - $tsize[3]);
    $x = (imagesx($image) - $dx) / 2;
    $y = (imagesy($image) - $dy) / 2 + $dy;
    
    //绘制文字,这里使用的是AnkeCalligraph TTF字体
    //AnkeCalligraph字体下载:http://blog.51yip.com/wp-content/uploads/2010/02/ttffont.tar.gz
    imagettftext($image, $size, 0, $x, $y, $red, $font, $text);
}

header("Content-Type:image/png");
imagepng($image);

Request the Image

<img src="dynamicImage.php?text=<?= urldecode("Hello PHP")?>" alt="dynamicImage"/>

Leave a Reply

Your email address will not be published.