Search code examples
phpimageimagecreatefrompng

Create PNG image with background consisting of squares in two colors


i'm tring to create PNG image with background consisting of squares in two colors, the squares is repeated horizontally or vertically as in the picture.

enter image description here

This is my code :

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

   for($y=0;$y<$maxwert;$y += $size){
     for($x=0;$x<$maxwert;$x+=$size){
      $r = rand(0,255);
      $g = rand(0,255);
      $b = rand(0,255);
      $color = imagecolorallocate($img, $r, $g, $b);
     
      imagefilledrectangle ($img, $x, $y, $x+$size ,$y+$size, $color);
    
     }
   }                 
// Save the image
imagepng($img, 'imagefilledrectangle.png');
imagedestroy($img);
?>

My output:

enter image description here


Solution

  • Create two colours outside the loop and then cycle one then the other

    <?php
    $maxwert = 300;
    $size = 20;
    $img = imagecreatetruecolor($maxwert, $maxwert);
    $colors = [
        imagecolorallocate($img, rand(0,255), rand(0,255) rand(0,255)),
        imagecolorallocate($img, rand(0,255), rand(0,255) rand(0,255))
    ];
    
    
    for($y=0;$y<$maxwert;$y += $size){
        for($x=0;$x<$maxwert;$x+=$size){
            imagefilledrectangle ($img, $x, $y, $x+$size ,$y+$size, $colors[(($x/$size)%2+($y/$size))%2]);    
        }
    }                
    // Save the image
    imagepng($img, 'imagefilledrectangle.png');
    imagedestroy($img);
    ?>