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

如何用phpqrcode生成渐变二维码?代码仅显示白色小方块

解决PHP生成渐变二维码显示白色小方块的问题

你的代码核心问题是直接将渐变图覆盖在二维码上,完全替换了原二维码的像素信息,导致二维码内容丢失,同时存在颜色计算逻辑复杂易出错的问题。以下是修正后的代码及关键说明:

修正后的代码

<?php
include 'phpqrcode/qrlib.php';

$qrtext = 'Gourav';
$qrsize = 10;

// 生成原始黑白二维码并捕获输出内容
ob_start();
// 明确指定二维码前景色(黑色)和背景色(白色)
QRcode::png($qrtext, false, QR_ECLEVEL_L, $qrsize, 2, false, 0x000000, 0xFFFFFF);
$qrcodeData = ob_get_contents();
ob_end_clean();

// 将二维码数据转换为图像资源,增加错误判断
$qrcodeImg = imagecreatefromstring($qrcodeData);
if (!$qrcodeImg) {
    die('无法创建二维码图像');
}

// 创建与二维码尺寸一致的渐变画布
$width = imagesx($qrcodeImg);
$height = imagesy($qrcodeImg);
$gradientImg = imagecreatetruecolor($width, $height);

// 定义渐变起始色(蓝色)和结束色(青色)
$startColor = [0, 0, 255];
$endColor = [0, 255, 255];

// 生成横向渐变效果
for ($x = 0; $x < $width; $x++) {
    // 计算当前横坐标对应的渐变RGB值
    $r = intval(($endColor[0] * $x + $startColor[0] * ($width - $x)) / $width);
    $g = intval(($endColor[1] * $x + $startColor[1] * ($width - $x)) / $width);
    $b = intval(($endColor[2] * $x + $startColor[2] * ($width - $x)) / $width);
    
    $currentColor = imagecolorallocate($gradientImg, $r, $g, $b);
    imageline($gradientImg, $x, 0, $x, $height, $currentColor);
}

// 遍历二维码像素,仅替换黑色码点为渐变颜色
$blackColor = imagecolorallocate($qrcodeImg, 0, 0, 0);
for ($x = 0; $x < $width; $x++) {
    for ($y = 0; $y < $height; $y++) {
        $pixelIndex = imagecolorat($qrcodeImg, $x, $y);
        if ($pixelIndex === $blackColor) {
            $gradientPixel = imagecolorat($gradientImg, $x, $y);
            imagesetpixel($qrcodeImg, $x, $y, $gradientPixel);
        }
    }
}

// 输出最终二维码图像
header('Content-Type: image/png');
imagepng($qrcodeImg);

// 释放图像资源
imagedestroy($qrcodeImg);
imagedestroy($gradientImg);
?>

关键修正说明

  • 保留二维码结构:不再直接覆盖二维码图像,仅替换黑色码点的颜色,保留白色背景,确保二维码可正常识别。
  • 简化渐变计算:用直观的RGB数组计算渐变值,避免复杂位运算带来的错误。
  • 增加异常判断:添加图像资源创建失败的判断,便于排查基础错误。
  • 明确颜色参数:生成二维码时指定前景/背景色,避免默认参数可能引发的兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:47:23