使用PHP生成各种颜色的随机棋盘图像

时间:2012-09-12 08:04:12

标签: php image-processing

我有以下PHP方法,在新用户首次注册时,在他们上传自己的用户之前为其生成个人资料图片。它所做的只是创建一个颜色鲜艳的方块 - 在显示没有个人资料照片的用户列表时,使界面看起来更有趣。

我怎样才能调整这种方法,以便创建一个随机颜色的棋盘?这样的事情:http://krazydad.com/bestiary/thumbs/random_pixels.jpg

public function generate_random_image($filename, $w = 200, $h = 200, $chosen_color = NULL) {

        if(!$chosen_color) {
            $color_options = Array("#6f0247", "#FF0569", "#FFF478", "#BAFFC0", "#27DB2D", "#380470", "#9D69D6");
            $random        = rand(0,sizeof($color_options));
            $chosen_color  = $color_options[$random];       
        }

        $rgb   = self::hex2rgb($chosen_color);              
        $image = imagecreatetruecolor($w, $h);

        for($row = 1; $row <= $h; $row++) {
            for($column = 1; $column <= $w; $column++) {    

               $color = imagecolorallocate ($image, $rgb[0] , $rgb[1], $rgb[2]);

               imagesetpixel($image,$column - 1 , $row - 1, $color);
            }

            $row_count++;
        }

        $filename = APP_PATH.$filename;

        imagepng($image, $filename);

        return $chosen_color;
    }

2 个答案:

答案 0 :(得分:2)

你怎么改变

$color = imagecolorallocate ($image, $rgb[0] , $rgb[1], $rgb[2]);

$color = imagecolorallocate ($image, rand(0,255), rand(0,255), rand(0,255));

然后,每个像素都有自己的颜色。只需绘制一个小图像,然后按比例缩放200%或300%(或其他任意数字),你就会得到漂亮的大块像素,就像你链接的图像一样。

答案 1 :(得分:0)

在迭代$row$column时,您应该增加步长到所需的像素大小,并在每次迭代时选择另一种颜色。

像素宽度= 20x20的示例:

    $pixel = 20;
    for($row = 0; $row <= $h / $pixel; $row++) {
        for($column = 0; $column <= $w/ $pixel; $column++) {    
           $rgb   = self::hex2rgb($color_options[rand(0,sizeof($color_options))]); 
           $color = imagecolorallocate ($image, $rgb[0] , $rgb[1], $rgb[2]);

           imagefilledrectangle(
               $image,
               $column*$pixel,
               $row*pixel,
               $column*$pixel+$pixel,
               $row*pixel+$pixel, 
               $color
           );
        }
    }