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

如何使用PHP生成双色方块横竖重复排列背景的PNG图片

问题原因

现有代码每次绘制方块时都会生成随机RGB值,每个方块颜色随机,无法实现双色交替的棋盘格效果。

修改后可直接运行的代码

<?php
$maxwert = 300;
$size = 20;
$img = imagecreatetruecolor($maxwert, $maxwert);

// 定义两种方块颜色,可自行调整RGB数值修改颜色
$colorA = imagecolorallocate($img, 255, 255, 255); // 示例为白色
$colorB = imagecolorallocate($img, 0, 0, 0); // 示例为黑色

for($y=0;$y<$maxwert;$y += $size){
    for($x=0;$x<$maxwert;$x+=$size){
        // 按行列索引和的奇偶性切换颜色,实现交替排列
        $current_color = (($x / $size) + ($y / $size)) % 2 == 0 ? $colorA : $colorB;
        imagefilledrectangle($img, $x, $y, $x + $size, $y + $size, $current_color);
    }
}                 

imagepng($img, 'imagefilledrectangle.png');
imagedestroy($img);
?>

如需调整两种颜色的具体取值,修改$colorA和$colorB对应的三个RGB参数即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:15:03