Special FX, Noise

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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Special FX, Scatter >>

Previous chapter: Special FX, Duotone

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.