dongye9182 2010-04-28 07:14
浏览 18
已采纳

如何使用PHP制作嘈杂的背景图像?

I'm looking to make an image that's just noise, maybe something like this:

alt text
(source: loriswebs.com)

Ideally I'd like to be able to change the colour as well. Any ideas on how to generate this?

  • 写回答

2条回答 默认 最新

  • douyingp82418 2010-04-28 08:04
    关注

    It's fairly straightforward to generate random noise. You can accomplish this pretty easily with some of PHP's image libraries, including the GD functions. I'm sure it would be similar in ImageMagick.

    If you wanted to generate completely random noise, you could use random values for every color and every pixel. That might look something like this with GD:

    //random colored noise
    $x = 150;
    $y = 150;
    $im = imagecreatetruecolor($x,$y);
    for($i = 0; $i < $x; $i++) {
        for($j = 0; $j < $y; $j++) {
            $color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
            imagesetpixel($im, $i, $j, $color);
        }
    }    
    header('Content-Type: image/png');
    imagepng($im);
    

    Generates this: alt text

    However, the example image that you posted clearly doesn't look like completely random color noise. It seems more like an arbitrary choice between one of two colors, either a somewhat-grey pixel or a somewhat-colored pixel. You could accomplish that more like this:

    //two-color random noise
    $x = 150;
    $y = 150;
    $im = imagecreatetruecolor($x,$y);
    $color1 = imagecolorallocate($im, 200, 240, 242);
    $color2 = imagecolorallocate($im,220,220,220);
    imagefill($im,0,0,$color1);
    for($i = 0; $i < $x; $i++) {
        for($j = 0; $j < $y; $j++) {
            if (mt_rand(0,1) == 1) imagesetpixel($im, $i, $j, $color2);
        }
    }
    header('Content-Type: image/png');
    imagepng($im);
    

    Generates this: alt text

    Your example seems a bit more complex still, with the pixels seeming to appear in small groups to produce a blockier appearance. You could emulate that by adjusting the loop logic if you wanted, or coloring small squares instead of individual pixels.

    An interesting thing about this type of generation is that you can actually see the breakdown of the rand() function on Windows platforms if you use it instead of mt_rand(). Discernible patterns can develop in the noise due to limitations in that function/platform combination.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大