使用普通的 GD Image 函数在 PHP 中创建渐变。该函数对颜色值使用 HTML 十六进制代码,然后将它们转换为具有 RGB 值的数组。
function image_gradientrect($img,$x,$y,$x1,$y1,$start,$end) {
if($x > $x1 || $y > $y1) {
return false;
}
$s = array(
hexdec(substr($start,0,2)),
hexdec(substr($start,2,2)),
hexdec(substr($start,4,2))
);
$e = array(
hexdec(substr($end,0,2)),
hexdec(substr($end,2,2)),
hexdec(substr($end,4,2))
);
$steps = $y1 - $y;
for($i = 0; $i < $steps; $i++) {
$r = $s[0] - ((($s[0]-$e[0])/$steps)*$i);
$g = $s[1] - ((($s[1]-$e[1])/$steps)*$i);
$b = $s[2] - ((($s[2]-$e[2])/$steps)*$i);
$color = imagecolorallocate($img,$r,$g,$b);
imagefilledrectangle($img,$x,$y+$i,$x1,$y+$i+1,$color);
}
return true;
}
$imgWidth = 300;
$imgHeight = 150;
$img = imagecreatetruecolor($imgWidth,$imgHeight);
image_gradientrect($img,0,0,$imgWidth,$imgHeight,'ff0000','0000ff');
/* Show In Browser as Image */
header('Content-Type: image/png');
imagepng($img);
/* Save as a File */
imagepng($img,'save.png');
/* Some Cleanup */
imagedestroy($img);
Run Code Online (Sandbox Code Playgroud)
只需在上面的代码中更改高度、宽度和颜色,它就会生成矩形图像。