项目中有时候会需要用到图片合并生成海报或二维码、小程序码以及添加水印文字、水印居中显示,方法如下:
/**
* 生成小程序码
* @throws \Exception
*/
public function getQrcodeImage($id)
{
$InspectionProject = InspectionProject::get($id);
$fileName = $InspectionProject->position . '-' . $InspectionProject->name . '.jpg';
if (file_exists(app()->getRootPath() . 'public/qrcode/' . $fileName)) {
return $fileName;
}
self::setApiUrl('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $this->getAccessToken());
self::setJsonParameter([
'page' => 'pages/scan-result',
'scene' => $id,
]);
self::setHeader([
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen(self::$parameter),
]);
self::post();
self::run();
$result = self::getResult();
if (!is_object($result)) {
$filePath = app()->getRootPath() . 'public/qrcode/' . $fileName;//文件路径
file_put_contents($filePath, $result);
$image = Image::open(app()->getRootPath() . 'public/templet.png');//模板图片
$image->water($filePath)
->text($InspectionProject->name, app()->getRootPath() . 'public/wryh.ttf', 35, '#233a66', [$this->widths($InspectionProject->name, app()->getRootPath() . 'public/wryh.ttf', 35, 430), 20])
->text($InspectionProject->position, app()->getRootPath() . 'public/wryh.ttf', 20, '#233a66', [$this->widths($InspectionProject->position, app()->getRootPath() . 'public/wryh.ttf', 20, 430), 90])
->save($filePath);
return $fileName;
}
return false;
}
计算文字相对当前位置的偏移量方法如下:
/**
* 计算文字的相对偏移度(用于居中)
* @param string $content 需要添加的文本
* @param string $font 本文字体文件路径
* @param int $fontsize 字体大小
* @param int $width 背景图宽度
* @return float
*/
public function widths(string $content, string $font, int $fontsize, int $width)
{
$array = imagettfbbox($fontsize, 0, $font, $content);
$widths = $array[2] - $array[0];
$widths = $width - $widths;
return $widths * 0.5;
}
生成效果如下: