图片合成概述
实现步骤
1. 加载原始图片
imagecreatefromjpeg($imagePath):加载JPEG图片imagecreatefrompng($imagePath):加载PNG图片imagecreatefromgif($imagePath):加载GIF图片
以下是一个示例代码:
$imagePath = './example.jpg';
$srcImage = imagecreatefromjpeg($imagePath);
2. 设置字体颜色、大小和样式
$fontColor = imagecolorallocate($srcImage, 255, 255, 255); // 白色
$fontSize = 20; // 字体大小
$fontPath = './arial.ttf'; // 字体路径
$textContent = 'Hello, World!';
$angle = 0; // 文字角度
imagettftext($srcImage, $fontSize, $angle, 10, 30, $fontColor, $fontPath, $textContent);
3. 处理文字换行
$textWidth = imagettfbbox($fontSize, $angle, $fontPath, $textContent);
$textWidth = $textWidth[2] - $textWidth[0];
// 根据图片宽度计算最大文字宽度
$maxTextWidth = imagesx($srcImage) - 20;
// 处理文字换行
$lines = explode("\n", $textContent);
foreach ($lines as $line) {
$lineWidth = imagettfbbox($fontSize, $angle, $fontPath, $line)[2] - $line[0];
if ($lineWidth > $maxTextWidth) {
$line = wordwrap($line, $maxTextWidth, "\n");
}
imagettftext($srcImage, $fontSize, $angle, 10, 50, $fontColor, $fontPath, $line);
}
4. 输出或保存合成图片
使用header设置正确的MIME类型后直接输出,或使用imagejpeg、imagepng、imagegif等函数保存到文件。以下是一个示例代码:
header('Content-Type: image/jpeg');
imagejpeg($srcImage);
// 保存到文件
// $outputPath = './output.jpg';
// imagejpeg($srcImage, $outputPath);