php生成渐变图片并添加水印
作者:admin 日期:2023-06-09
现在还有个问题,就是渐变色只能是灰色,不清楚什么原因。。
PHP代码
- // 创建画布
- $imageWidth = 720;
- $imageHeight = 480;
- $image = imagecreatetruecolor($imageWidth, $imageHeight);
- // 生成随机渐变
- $startColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
- $endColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
- // 填充渐变背景
- for ($y = 0; $y < $imageHeight; $y++) {
- $progress = $y / ($imageHeight - 1);
- $r = lerp($startColor, $endColor, $progress, 'red');
- $g = lerp($startColor, $endColor, $progress, 'green');
- $b = lerp($startColor, $endColor, $progress, 'blue');
- $color = imagecolorallocate($image, $r, $g, $b);
- imagefilledrectangle($image, 0, $y, $imageWidth - 1, $y, $color);
- }
- // 添加水印文字
- $watermarkText = $title;
- $font = 'fonts/msyh.ttc'; // 替换为实际的字体文件路径
- $fontSize = 20;
- $fontColor = imagecolorallocate($image, 255, 255, 255);
- $padding = 10;
- $box = imagettfbbox($fontSize, 0, $font, $watermarkText);
- $textWidth = $box[2] - $box[0];
- $textHeight = $box[1] - $box[7];
- $textX = $imageWidth - $textWidth - $padding;
- $textY = $imageHeight - $textHeight - $padding;
- imagettftext($image, $fontSize, 0, $textX, $textY, $fontColor, $font, $watermarkText);
- // 输出图片
- header('Content-type: image/png');
- imagepng($image);
- imagedestroy($image);
- // 辅助函数,用于线性插值
- function lerp($startColor, $endColor, $progress, $channel) {
- $start = $startColor & 0xFF;
- $end = $endColor & 0xFF;
- return (int) round($start * (1 - $progress) + $end * $progress);
- }
评论: 0 | 引用: 0 | 查看次数: 38
发表评论
广告位