萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP GD 实现颜色渐变图片生成:从黑到白 256 级灰度条

核心代码

<?php
// 创建 255x255 画布
$im = imagecreate(255, 255);

// 分配背景色(黑)
$bg = imagecolorallocate($im, 0, 0, 0);

// 逐行绘制灰度矩形
for ($i = 255; $i >= 0; $i--) {
    // 灰度色:R=G=B=i
    $color = imagecolorallocate($im, $i, $i, $i);
    // 画高度为 1 像素的横条
    imagefilledrectangle($im, 0, $i, 255, 1, $color);
}

// 输出 PNG
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

效果说明

生成一张 255×255 像素的 PNG 图片,顶部纯白(255,255,255),底部纯黑(0,0,0),中间平滑过渡 256 级灰度。

扩展:任意双色线性渐变

<?php
function gradientImage($w, $h, $startRGB, $endRGB, $direction = 'vertical') {
    $im = imagecreatetruecolor($w, $h);
    $steps = $direction === 'vertical' ? $h : $w;
    for ($i = 0; $i < $steps; $i++) {
        $ratio = $i / ($steps - 1);
        $r = (int)($startRGB[0] + ($endRGB[0] - $startRGB[0]) * $ratio);
        $g = (int)($startRGB[1] + ($endRGB[1] - $startRGB[1]) * $ratio);
        $b = (int)($startRGB[2] + ($endRGB[2] - $startRGB[2]) * $ratio);
        $color = imagecolorallocate($im, $r, $g, $b);
        if ($direction === 'vertical') {
            imagefilledrectangle($im, 0, $i, $w, 1, $color);
        } else {
            imagefilledrectangle($im, $i, 0, 1, $h, $color);
        }
    }
    return $im;
}

// 红->蓝横向渐变
$img = gradientImage(400, 100, [255,0,0], [0,0,255], 'horizontal');
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);

性能提示

  • imagecreatetruecolor 支持 24-bit 真彩色,imagecreate 仅 256 色调色板,渐变必须用 truecolor。
  • 大尺寸图片循环分配颜色较慢,可预计算调色表或使用 imagefilledpolygon 近似。
  • 高性能场景考虑用 Imagick 扩展:$im->gradientImage('red', 'blue', $w, $h, Imagick::GRADIENT_LINEAR)。
copyright © 萬盛學電腦網 all rights reserved