You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP生成二维码合并到编辑后的JPG文件后输出无二维码怎么解决

故障排查与修复代码

核心问题点

  • 二维码合并逻辑仅在二维码文件首次生成时触发:你将imagecopymerge逻辑写在了if (!file_exists($pngAbsoluteFilePath))判断内,当temp目录下已存在对应文件名的二维码时,会直接跳过加载和合并二维码的步骤,导致图片上没有二维码。
  • 缺少必要的权限与资源校验:未校验temp目录是否有写入权限、二维码文件是否生成成功、imagecreatefrompng是否返回有效图片资源,任意环节出错都会导致二维码无法加载。
  • 硬编码的合并尺寸不匹配:imagecopymerge中固定写死了宽100、高47的参数,若phpqrcode生成的二维码实际尺寸与该值不符,会出现显示异常甚至完全不显示的问题。
  • 变量合法性未校验:未校验$reg、$name变量是否有有效值,若$reg为空会生成错误的文件名,导致文件判断逻辑异常。

修复后的完整代码

<?php
ini_set('memory_limit', '64M');
$jpg_image = imagecreatefromjpeg('certificate.jpg');
if ($jpg_image) {
    // 提前校验必要变量合法性,可根据实际业务调整默认值
    $name = $name ?? '默认文本';
    $reg = $reg ?? '默认标识';
    $text = $name;
    $textc = imagecolorallocate($jpg_image, 0, 0, 0);
    $font_path = '../images/CHOPS___.TTF';
    imagettftext($jpg_image, 42, 0, 300, 400, $textc, $font_path, $text);
    
    include('phpqrcode/qrlib.php');
    $tempDir = 'temp/';
    // 自动创建不存在的temp目录,保证写入权限
    if (!is_dir($tempDir)) {
        mkdir($tempDir, 0755, true);
    }
    $fileName = 'tmp_'.md5($reg).'.png';
    $pngAbsoluteFilePath = $tempDir.$fileName;
    
    // 不存在二维码则生成
    if (!file_exists($pngAbsoluteFilePath)) {
        QRcode::png($text, $pngAbsoluteFilePath);
    }
    // 无论是否首次生成,都执行二维码加载合并逻辑
    if (file_exists($pngAbsoluteFilePath)) {
        $qrcode = imagecreatefrompng($pngAbsoluteFilePath);
        if ($qrcode) {
            // 动态获取二维码实际尺寸,避免硬编码尺寸不匹配
            $qr_width = imagesx($qrcode);
            $qr_height = imagesy($qrcode);
            imagecopymerge($jpg_image, $qrcode, 10, 10, 0, 0, $qr_width, $qr_height, 75);
            imagedestroy($qrcode);
        }
    }
    
    header('Content-Type: image/jpeg');
    imagejpeg($jpg_image);
    imagedestroy($jpg_image);
}
?>

内容的提问来源于stack exchange,提问作者sridhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:00:03