php之使用gd库给图片添加文字以及图片:
这个功能其实很简单,设计出图片模板,然后再指定的位置替换上 指定的内容即可,代码如下:
<?php
namespace App\Service;
use Symfony\Component\Validator\Constraints\Date;
class CertificationService
{
public static string $signatureName = 'John Doe';
public static string $prefix = 'certification';
/**
* @throws \Exception
*/
public static function generateCertification($name, $course, $createdAt): string
{
$imgPath = './statics/img/certificationTemplate.png';
$fontPathB = './statics/img/suisse/SuisseIntl-SemiBold.otf'; // 600 字体文件
$fontPathM = './statics/img/suisse/SuisseIntl-Medium.otf'; // 500 字体文件
$signaturePath = './statics/img/signature.png';
$img = imagecreatefrompng($imgPath);
$font_size = 18;
$color = imagecolorallocate($img, 0, 0, 0);
if ($name) {
$x = 1080;
$y = 301 + 20; // 404.6 - (10 + ( 28 - 20 ) / 2)
//将$name 方法模板的水平中间位置,这个要先通过 imagettfbbox 将文字格式化为文字盒子,再计算出这个文字盒子的宽高,用 (总宽度 - 盒子宽度)/2,得到中间位置
$nameBox = imagettfbbox($font_size, 0, $fontPathB, $name);
self::imageToText($img, $font_size, ceil(($x - $nameBox[2]) / 2), $y, $color, $fontPathB, $name);
}
$x = 581;
$y = 344 + 14 + 8; // 489.6 - (10 + (28 - 20) / 2)
self::imageToText($img, $font_size, $x, $y, $color, $fontPathB, $course);
//sig 将signature 图片添加到模板的指定位置
$overlayImage = imagecreatefrompng($signaturePath);
list($overlayWidth, $overlayHeight) = getimagesize($signaturePath);
imagecopy($img, $overlayImage, 656, 456, 0, 0, $overlayWidth, $overlayHeight);
if ($name) {
$number = '';
array_map(function ($item) use (&$number) {
$number .= substr($item, 0, 1);
}, explode(" ", ucwords($course)));
$number .= ' ' . random_int(10000, 99999);
$x = 357;
$yNumber = 503 + 24; // 554.6 + 20 + (28 - 20) / 2
self::imageToText($img, 16, $x, $yNumber, $color, $fontPathM, $number);
$time = \date('Y.m.d', time());
$yTime = 537 + 24;
self::imageToText($img, 16, $x, $yTime, $color, $fontPathM, $time);
}
$date = (new \DateTime())->format('Y-m-d');
$ext = substr($imgPath, strripos($imgPath, '.'));
$destDir = 'upload' . '/' . self::$prefix . '/' . $date . '/';
$filename = md5(microtime()) . $ext;
if (!is_dir($destDir)) {
@mkdir($destDir, 0777, true);
}
imagepng($img, './' . $destDir . $filename);
imagedestroy($img);
return $destDir . $filename;
}
public static function imageToText($img, $font_size, $x, $y, $color, $fontPath, $text): void
{
imagettftext($img, $font_size, 0, $x, $y, $color, $fontPath, $text);
}
}
