在 php 中绘制矩形无效

Drawing rectangles in php not working

我正在 php 中创建一个图像,并用填充有颜色的 10x10 像素矩形填充它。

$image = imagecreate(150,150);
$background = imagecolorallocate($image, 0, 0, 0); //black background
for ($row=0; $row < 15; $row++) { 
    for ($col=0; $col < 15; $col++) { 
        $x1 = 10* $col;
        $y1 = 10*$row;
        $x2 = 10*($col + 1);
        $y2 = 10*($row + 1);

        imagefilledrectangle($image, $x1,$y1,$x2,$y2, imagecolorallocate($image, 100,100,100)); //grey rectangle
    }
}

imagepng($image, "ciph.png");

这适用于不大于 150x150 像素的小图像,我得到一个完全灰色填充的矩形。但是当我尝试更大的图像时。它只将矩形添加到图像的一部分。知道是什么原因造成的吗?我可以绘制的单个对象的数量似乎有限制。

15x15

18x18

我数了一下,似乎只画了 256 个矩形...看起来不是巧合,那是 2 的 8 次方。

如有任何帮助,我们将不胜感激!谢谢。

问题在于您如何创建图像。如果您将第一行更改为:

$image = imagecreate(150,150);

至:

$image = imagecreatetruecolor(150,150);

它将允许在图像上绘制超过 256 个矩形。

imagecreatetruecolor() 还默认为图像提供黑色背景,而不是 imagecreate() 提供的空白背景,因此您也不需要第二行。