一个分享WordPress、Zblog、Emlog、Typecho等主流博客的教程网站!
当前位置:网站首页 > 编程知识 > 正文

php自动实现两张头像图片拼成一张图片

作者:xlnxin发布时间:2026-07-22分类:编程知识浏览:158


导读:<?php/** * 图片自动拼接工具 (带清晰度选项版 + 链接净化) * 功能:将多行图...
<?php
/**
 * 图片自动拼接工具 (带清晰度选项版 + 链接净化)
 * 功能:将多行图片URL两两拼接,中间留白,自动裁剪为正方形
 * 新增:可选是否应用锐化滤镜
 * 新增:自动去除图片链接中的问号及后续参数
 */
include 'config.inc.php'; 
error_reporting(E_ALL);
ini_set('display_errors', 0); 

$generatedImages = [];
$errorMsg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['image_urls'])) {
    $urls = array_filter(array_map('trim', explode("\n", $_POST['image_urls'])));
    $urls = array_values($urls);
    
    // --- 新增逻辑开始:去除URL参数 ---
    // $cleanUrls = [];
    // foreach ($urls as $url) {
    //     // 如果包含问号,只保留问号前面的部分
    //     if (strpos($url, '?') !== false) {
    //         $url = substr($url, 0, strpos($url, '?'));
    //     }
    //     $cleanUrls[] = $url;
    // }
    // $urls = $cleanUrls; // 使用净化后的链接数组
    // // --- 新增逻辑结束 ---

    // 获取是否勾选了“增强清晰度”
    $applySharpen = isset($_POST['apply_sharpen']) && $_POST['apply_sharpen'] === '1';

    if (count($urls) < 2) {
        $errorMsg = "请至少输入两张图片地址。";
    } else {
        if (!extension_loaded('gd')) {
            $errorMsg = "错误:服务器未安装 GD 库,无法处理图片。";
        } else {
            for ($i = 0; $i < count($urls); $i += 2) {
                if (!isset($urls[$i+1])) break;

                $url1 = $urls[$i];
                $url2 = $urls[$i+1];

                $img1 = @getImageResource($url1);
                $img2 = @getImageResource($url2);

                if ($img1 && $img2) {
                    // 传入 $applySharpen 参数,决定是否锐化
                    $square1 = createSquareImage($img1, 600, $applySharpen);
                    $square2 = createSquareImage($img2, 600, $applySharpen);

                    imagedestroy($img1);
                    imagedestroy($img2);

                    // 创建画布 (1220x600)
                    $canvas = imagecreatetruecolor(1210, 600);
                    $white = imagecolorallocate($canvas, 255, 255, 255);
                    imagefill($canvas, 0, 0, $white);

                    // 拼接图片
                    imagecopy($canvas, $square1, 0, 0, 0, 0, 600, 600);
                    imagecopy($canvas, $square2, 610, 0, 0, 0, 600, 600);

                    imagedestroy($square1);
                    imagedestroy($square2);

                    // 输出为 Base64
                    ob_start();
                    imagejpeg($canvas, null, 95); 
                    $imgData = ob_get_contents();
                    ob_end_clean();

                    imagedestroy($canvas);

                    $generatedImages[] = 'data:image/jpeg;base64,' . base64_encode($imgData);
                } else {
                    $errorMsg .= "无法读取图片:$url1 或 $url2 <br>";
                }
            }
        }
    }
}

function getImageResource($url) {
    // 设置 User-Agent 防止部分网站防盗链拦截
    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
            'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ]
    ]);
    
    $data = @file_get_contents($url, false, $context);
    if (!$data) return false;
    return @imagecreatefromstring($data);
}

/**
 * 将图片处理为指定尺寸的正方形
 * @param resource $sourceImage 原图资源
 * @param int $size 目标尺寸 (宽=高)
 * @param bool $sharpen 是否应用锐化滤镜
 */
function createSquareImage($sourceImage, $size, $sharpen = true) {
    $originalWidth = imagesx($sourceImage);
    $originalHeight = imagesy($sourceImage);

    $square = imagecreatetruecolor($size, $size);
    
    // 保持透明度
    imagealphablending($square, false);
    imagesavealpha($square, true);
    $transparent = imagecolorallocatealpha($square, 255, 255, 255, 127);
    imagefilledrectangle($square, 0, 0, $size, $size, $transparent);

    // 计算裁剪区域 (中心裁剪)
    $srcX = 0;
    $srcY = 0;
    $srcW = $originalWidth;
    $srcH = $originalHeight;

    if ($originalWidth > $originalHeight) {
        $srcX = intval(($originalWidth - $originalHeight) / 2);
        $srcW = $originalHeight;
    } else {
        $srcY = intval(($originalHeight - $originalWidth) / 2);
        $srcH = $originalWidth;
    }

    // 高质量重采样
    imagecopyresampled($square, $sourceImage, 0, 0, $srcX, $srcY, $size, $size, $srcW, $srcH);

    // 如果勾选了锐化,则应用滤镜
    if ($sharpen) {
        $sharpenMatrix = array(
            array(-1.2, -1, -1.2),
            array(-1, 20, -1), 
            array(-1.2, -1, -1.2)
        );
        $div = 10; 
        imageconvolution($square, $sharpenMatrix, $div, 0);
    }

    return $square;
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="referrer" content="never" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片拼接工具 (可选清晰度)</title>
    <style>
        body { font-family: "Microsoft YaHei", sans-serif; background: #f5f5f5; padding: 20px; max-width: 1280px; margin: 0 auto; }
        .container { background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h2 { margin-top: 0; color: #333; }
        textarea { width: 100%; height: 150px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; font-family: monospace; resize: vertical; }
        .btn { background: #007BFF; color: #fff; border: none; padding: 12px 30px; border-radius: 4px; cursor: pointer; font-size: 16px; margin-top: 15px; transition: background 0.2s; }
        .btn:hover { background: #0056b3; }
        .result-area { margin-top: 40px; display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
        .result-item img { width: 100%; height: auto; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); display: block; }
        .error { color: #dc3545; background: #f8d7da; padding: 15px; border-radius: 4px; margin-bottom: 20px; border: 1px solid #f5c6cb; }
        .desc { color: #666; font-size: 14px; margin-bottom: 10px; }
        
        /* 新增复选框样式 */
        .options { margin-top: 15px; display: flex; align-items: center; }
        .options label { cursor: pointer; font-size: 14px; color: #333; user-select: none; }
        .options input[type="checkbox"] { margin-right: 8px; transform: scale(1.2); }
    </style>
</head>
<body>
<div>
    <h2>图片自动拼接工具</h2>
    <p>请输入图片地址(每行一个),程序将自动去除链接参数并按顺序每两张拼接。</p>
    
    <form method="POST">
        <textarea name="image_urls" placeholder="请输入图片URL,每行一个"></textarea>
        
        <!-- 新增选项按钮 -->
        <div>
            <label>
                <input type="checkbox" name="apply_sharpen" value="1" >
                增强图片清晰度(应用锐化滤镜)
            </label>
        </div>

        <button type="submit">开始生成</button>
    </form>

    <?php if ($errorMsg): ?>
        <div><?php echo $errorMsg; ?></div>
    <?php endif; ?>

    <div>
        <?php foreach ($generatedImages as $imgSrc): ?>
            <div>
                <img src="<?php echo $imgSrc; ?>" alt="拼接结果">
            </div>
        <?php endforeach; ?>
    </div>
</div>
</body>
</html>

标签:服务器程序htmldivphp