家明故事

PHP代理图片生成脚本(支持随机背景图片)

家明 0 0

根据标题生成图片,可设置参数支持:标题、宽、高、文字颜色、指定背景图、背景色等。以下是一个增强版的PHP脚本,支持从预置文件夹中随机选择背景图片:

php
<?php
// proxy-image.php - 代理图片生成脚本(支持随机背景图片)

// 设置内容类型为PNG图片
header('Content-Type: image/png');

// 启用错误报告(仅在开发环境中使用)
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// 获取文章标题参数
$title = isset($_GET['title']) ? trim($_GET['title']) : '';

// 如果没有提供标题,使用默认值
if (empty($title)) {
    $title = '文章标题未提供';
}

// 解码URL编码的标题
$title = urldecode($title);

// 安全过滤,移除可能有害的HTML/JS代码
$title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');

// 设置图片尺寸
$width = isset($_GET['width']) ? intval($_GET['width']) : 800;
$height = isset($_GET['height']) ? intval($_GET['height']) : 400;

// 限制图片尺寸范围
$width = max(300, min(2000, $width));
$height = max(150, min(1500, $height));

// 获取文字颜色参数
$textColor = isset($_GET['color']) ? $_GET['color'] : 'ffffff';

// 验证颜色格式
if (!preg_match('/^[0-9a-fA-F]{6}$/', $textColor)) {
    $textColor = 'ffffff';
}

// 背景图片文件夹路径
$backgroundsDir = __DIR__ . '/backgrounds';

// 支持的图片扩展名
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];

// 尝试获取背景图片
$backgroundImage = null;

// 检查是否指定了特定的背景图片
$bgImageParam = isset($_GET['bg_image']) ? $_GET['bg_image'] : '';

if (!empty($bgImageParam) && file_exists($backgroundsDir . '/' . $bgImageParam)) {
    // 使用指定的背景图片
    $bgImagePath = $backgroundsDir . '/' . $bgImageParam;
    $backgroundImage = loadImageFromFile($bgImagePath);
} else {
    // 随机选择背景图片
    $backgroundImage = getRandomBackgroundImage($backgroundsDir, $allowedExtensions);
}

// 创建图片资源
if ($backgroundImage) {
    // 使用背景图片
    $image = $backgroundImage;
    
    // 调整背景图片尺寸
    $originalWidth = imagesx($image);
    $originalHeight = imagesy($image);
    
    // 创建目标尺寸的画布
    $resizedImage = imagecreatetruecolor($width, $height);
    
    // 调整图片尺寸并保持宽高比(裁剪模式)
    $ratio = max($width / $originalWidth, $height / $originalHeight);
    $newWidth = $originalWidth * $ratio;
    $newHeight = $originalHeight * $ratio;
    
    // 计算裁剪位置
    $x = ($newWidth - $width) / 2;
    $y = ($newHeight - $height) / 2;
    
    // 调整图像大小
    imagecopyresampled($resizedImage, $image, -$x, -$y, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
    
    // 释放原图资源
    imagedestroy($image);
    
    // 使用调整后的图片
    $image = $resizedImage;
    
    // 添加半透明黑色遮罩以提高文字可读性
    $overlayColor = imagecolorallocatealpha($image, 0, 0, 0, 90); // 90 = 35%透明度
    imagefilledrectangle($image, 0, 0, $width, $height, $overlayColor);
} else {
    // 如果没有背景图片,使用纯色背景
    $image = imagecreatetruecolor($width, $height);
    
    // 获取背景色参数
    $bgColor = isset($_GET['bg']) ? $_GET['bg'] : '3498db';
    
    // 验证颜色格式
    if (!preg_match('/^[0-9a-fA-F]{6}$/', $bgColor)) {
        $bgColor = '3498db';
    }
    
    // 将十六进制颜色转换为RGB值
    $bgRgb = hexToRgb($bgColor);
    $backgroundColor = imagecolorallocate($image, $bgRgb[0], $bgRgb[1], $bgRgb[2]);
    
    // 填充背景色
    imagefill($image, 0, 0, $backgroundColor);
}

// 将十六进制颜色转换为RGB值的函数
function hexToRgb($hex) {
    $hex = str_replace('#', '', $hex);
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    return [$r, $g, $b];
}

// 加载图片文件的函数
function loadImageFromFile($filePath) {
    $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            return imagecreatefromjpeg($filePath);
        case 'png':
            return imagecreatefrompng($filePath);
        case 'gif':
            return imagecreatefromgif($filePath);
        default:
            return null;
    }
}

// 获取随机背景图片的函数
function getRandomBackgroundImage($dir, $allowedExtensions) {
    if (!is_dir($dir)) {
        return null;
    }
    
    // 获取目录中的所有文件
    $files = [];
    $dirHandle = opendir($dir);
    
    while (($file = readdir($dirHandle)) !== false) {
        if ($file === '.' || $file === '..') {
            continue;
        }
        
        $filePath = $dir . '/' . $file;
        $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
        
        // 检查文件是否为支持的图片格式
        if (in_array($extension, $allowedExtensions)) {
            $files[] = $filePath;
        }
    }
    
    closedir($dirHandle);
    
    // 如果没有找到图片,返回null
    if (empty($files)) {
        return null;
    }
    
    // 随机选择一张图片
    $randomIndex = array_rand($files);
    $randomImagePath = $files[$randomIndex];
    
    // 加载图片
    return loadImageFromFile($randomImagePath);
}

// 获取颜色值
$textRgb = hexToRgb($textColor);

// 为图片分配颜色
$titleColor = imagecolorallocate($image, $textRgb[0], $textRgb[1], $textRgb[2]);

// 设置字体路径
$fontPath = __DIR__ . '/fonts/NotoSansSC-Regular.ttf';

// 如果自定义字体不存在,使用GD默认字体
$useCustomFont = file_exists($fontPath);

// 设置字体大小(根据图片宽度自适应)
$baseFontSize = $width / 20; // 基础字体大小
$fontSize = min($baseFontSize, 40); // 最大40px
$fontSize = max($fontSize, 16); // 最小16px

// 计算标题文本的边界框
if ($useCustomFont) {
    // 使用自定义字体(支持中文)
    $textBox = imagettfbbox($fontSize, 0, $fontPath, $title);
    $textWidth = $textBox[2] - $textBox[0];
    $textHeight = $textBox[1] - $textBox[7];
} else {
    // 使用默认字体(只支持英文)
    $textWidth = imagefontwidth(5) * strlen($title);
    $textHeight = imagefontheight(5);
    $fontSize = 5; // GD内置字体大小
}

// 如果标题太长,自动换行
$maxLineWidth = $width * 0.8; // 最大宽度为图片宽度的80%
$lines = [];

if ($useCustomFont && $textWidth > $maxLineWidth) {
    // 中文换行处理
    $line = '';
    $chars = preg_split('//u', $title, -1, PREG_SPLIT_NO_EMPTY);
    
    foreach ($chars as $char) {
        $testLine = $line . $char;
        $testBox = imagettfbbox($fontSize, 0, $fontPath, $testLine);
        $testWidth = $testBox[2] - $testBox[0];
        
        if ($testWidth > $maxLineWidth && !empty($line)) {
            $lines[] = $line;
            $line = $char;
        } else {
            $line = $testLine;
        }
    }
    
    if (!empty($line)) {
        $lines[] = $line;
    }
    
    // 重新计算总高度
    $lineHeight = $textHeight * 1.2; // 行高为字高的1.2倍
    $totalTextHeight = count($lines) * $lineHeight;
} else {
    // 单行文本
    $lines = [$title];
    $lineHeight = $textHeight * 1.2;
    $totalTextHeight = $lineHeight;
}

// 计算文本位置(居中)
$textY = ($height - $totalTextHeight) / 2 + $textHeight;

// 添加文字阴影效果(可选)
$shadowColor = imagecolorallocate($image, 0, 0, 0);

// 逐行渲染文本
foreach ($lines as $i => $line) {
    if ($useCustomFont) {
        // 计算当前行的宽度
        $lineBox = imagettfbbox($fontSize, 0, $fontPath, $line);
        $lineWidth = $lineBox[2] - $lineBox[0];
        $textX = ($width - $lineWidth) / 2;
        
        // 添加阴影
        imagettftext($image, $fontSize, 0, $textX + 2, $textY + 2 + ($i * $lineHeight), $shadowColor, $fontPath, $line);
        // 添加文字
        imagettftext($image, $fontSize, 0, $textX, $textY + ($i * $lineHeight), $titleColor, $fontPath, $line);
    } else {
        $lineWidth = imagefontwidth(5) * strlen($line);
        $textX = ($width - $lineWidth) / 2;
        
        // 添加阴影
        imagestring($image, $fontSize, $textX + 2, $textY - $textHeight + 2 + ($i * $lineHeight), $line, $shadowColor);
        // 添加文字
        imagestring($image, $fontSize, $textX, $textY - $textHeight + ($i * $lineHeight), $line, $titleColor);
    }
}

// 可选:添加网站标识
$siteText = "代理图片生成器";
$siteFontSize = 12;
if ($useCustomFont) {
    $siteBox = imagettfbbox($siteFontSize, 0, $fontPath, $siteText);
    $siteWidth = $siteBox[2] - $siteBox[0];
    imagettftext($image, $siteFontSize, 0, $width - $siteWidth - 10, $height - 10, $titleColor, $fontPath, $siteText);
}

// 输出PNG图片
imagepng($image);

// 释放内存
imagedestroy($image);

exit;

安装和使用说明

1. 目录结构

text
你的网站目录/
├── proxy-image.php          # 主脚本文件
├── backgrounds/             # 背景图片文件夹(需要手动创建)
│   ├── bg1.jpg
│   ├── bg2.png
│   └── bg3.jpg
└── fonts/                   # 字体文件夹(可选)
    └── NotoSansSC-Regular.ttf

2. 创建背景图片文件夹

bash
# 在脚本同一目录下创建backgrounds文件夹
mkdir backgrounds

# 上传一些背景图片到这个文件夹
# 支持的格式:JPG, JPEG, PNG, GIF

3. 使用方式

基本用法(随机背景)

text
proxy-image.php?title=你的文章标题

指定特定背景图片

text
proxy-image.php?title=你的文章标题&bg_image=bg1.jpg

高级参数

text
proxy-image.php?title=你的文章标题&width=600&height=300&color=ffffff

4. 参数说明

参数说明默认值
title要显示的文章标题"文章标题未提供"
width图片宽度(300-2000像素)800
height图片高度(150-1500像素)400
color文字颜色(十六进制,不带#)ffffff(白色)
bg_image指定背景图片文件名随机选择
bg当没有背景图片时使用的背景色3498db(蓝色)

5. 背景图片处理特性

  1. 随机选择:脚本会自动从backgrounds文件夹中随机选择一张图片作为背景

  2. 智能裁剪:背景图片会自动调整大小并裁剪以适应指定的尺寸

  3. 遮罩层:在背景图片上添加半透明黑色遮罩,确保文字清晰可读

  4. 自动换行:长标题会自动换行以适应图片宽度

6. 注意事项

  1. 确保backgrounds文件夹有读取权限

  2. 背景图片建议使用高分辨率图片以获得最佳效果

  3. 如果需要中文支持,请下载中文字体文件并放入fonts文件夹

  4. 脚本会自动处理各种图片格式,但建议使用JPG或PNG格式以获得更好的性能

这个脚本可以用于博客文章、社交媒体分享、内容预览等多种场景,生成美观且专业的图片。

标签:PHP  图片生成  

打赏

上一篇:PHP利用header跳转失效的解决方法

下一篇:没有了

发表评论