OBJUI

PHP合成图片

2025-05-22 18:05:27 2759
```php /** * 生成带二维码海报 */ public static function createPoster($code) { try{ $qrcode = self::createQrcode($code); $qrcodeUrl = app()->getRootPath().'data/runtime/temp/'.uniqid().'.png'; file_put_contents($qrcodeUrl, file_get_contents($qrcode)); $bg_url = app()->getRootPath() . 'public/static/images/bg.jpg'; // 创建第一张图片的资源 $backgroundImage = imagecreatefromjpeg($bg_url); //w279 h1108 // 创建第二张图片的资源 $qrCodeImage = imagecreatefromjpeg($qrcodeUrl); // 获取海报背景的宽度和高度 $backgroundWidth = imagesx($backgroundImage); $backgroundHeight = imagesy($backgroundImage); // 获取二维码的宽度和高度 $qrCodeWidth = 180; $qrCodeHeight = 180; // 计算二维码的位置,使其靠页脚放置 $qrCodeX = ($backgroundWidth - $qrCodeWidth) / 2; // 根据需要调整位置 $qrCodeY = ($backgroundHeight - $qrCodeHeight) - 146; // 根据需要调整位置 // 创建缩放后的二维码图像资源 $scaleFactor = 180 / imagesy($qrCodeImage); // 计算缩放后的二维码尺寸 $scaledWidth = imagesx($qrCodeImage) * $scaleFactor; $scaledHeight = imagesy($qrCodeImage) * $scaleFactor; $scaledQRCodeImage = imagecreatetruecolor($scaledWidth, $scaledHeight); imagecopyresampled( $scaledQRCodeImage, // 目标图像资源 $qrCodeImage, // 源图像文件路径 0, // 目标图像的 x 坐标 0, // 目标图像的 y 坐标 0, // 源图像的 x 坐标 0, // 源图像的 y 坐标 $scaledWidth, // 目标图像的宽度 $scaledHeight, // 目标图像的高度 imagesx($qrCodeImage), // 源图像的宽度 imagesy($qrCodeImage) // 源图像的高度 ); // 将二维码复制到海报背景上 imagecopy($backgroundImage, $scaledQRCodeImage, $qrCodeX, $qrCodeY, 0, 0, $scaledWidth, $scaledHeight); // 添加文字:123456(左下角) $font = app()->getRootPath() . 'public/static/fonts/simhei.ttf'; // 确保有中文字体文件 $text = "123456"; $fontSize = 20; // 字体大小 $textColor = imagecolorallocate($backgroundImage, 0, 0, 0); // 黑色文字 // 计算文字位置(左下角,留出10px边距) $textBox = imagettfbbox($fontSize, 0, $font, $text); $textWidth = $textBox[2] - $textBox[0]; $textHeight = $textBox[1] - $textBox[5]; $textX = 10; // 左边距 $textY = $backgroundHeight - $textHeight - 10; // 底部边距 // 绘制文字 imagettftext( $backgroundImage, $fontSize, 0, $textX, $textY, $textColor, $font, $text ); // 输出合成后的海报图像 $outputImagePath = app()->getRootPath().'data/runtime/temp/'.uniqid().'.jpg'; // 输出图像的保存路径 imagejpeg($backgroundImage, $outputImagePath); // 释放资源 imagedestroy($backgroundImage); imagedestroy($qrCodeImage); imagedestroy($scaledQRCodeImage); // 新增:释放缩放后的二维码资源 return $outputImagePath; }catch(Exception $e){ Log::channel('wx')->info($e->getMessage()); return ''; } } ```
更多精彩,请关注公众号

微信公众号

评论:
热门文章: