11.2.22 Special FX, NoiseThis is NOT the latest copy of this book; click here for the latest version.
Although noise is something more commonly associated with audio, there is a graphical equivalent too. If you think of the term "white noise", it usually refers to randomly ordered white speckles on a black screen; noise in general is the same, except based upon existing colours as opposed to just white. Much of the algorithm for noise is the same as greyscale: cycle through each pixel, get the red, green, and blue value for it, add or subtract a small amount from each number, and set the new value. Of these, you should already be familiar with items 1, 2, and 4.
Here is how the noise function looks in PHP:
function noise (&$image) {
$imagex = imagesx($image);
$imagey = imagesy($image);
for ($x = 0; $x < $imagex; ++$x) {
for ($y = 0; $y < $imagey; ++$y) {
if (rand(0,1)) {
$rgb = imagecolorat($image, $x, $y);
red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
$modifier = rand(-20,20);
$red += $modifier;
$green += $modifier;
$blue += $modifier;
if ($red > 255) $red = 255;
if ($green > 255) $green = 255;
if ($blue > 255) $blue = 255;
if ($red < 0) $red = 0;
if ($green < 0) $green = 0;
if ($blue < 0) $blue = 0;
$newcol = imagecolorallocate($image, $red, $green, $blue);
imagesetpixel($image, $x, $y, $newcol);
}
}
}
}
Compared to the greyscale() function, there are only four new lines of code, so most of it should be easy. The new parts - the lines using $modifier - are there to randomise the colours a little bit. By randomly choosing a value between -10 and 10 and adding it to the existing red, green, and blue values for a pixel, the function will either lighten or darken each pixel just a little. As each pixel will be randomised separately the whole picture should look a little different each time.

|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|