11.2.23 Special FX, ScatterThis is NOT the latest copy of this book; click here for the latest version.
One effect that can look particularly effective if used correctly is scatter, which basically sets the colour of the current pixel to that of another pixel close by, and vice versa, effectively swapping the two pixels. The effect is called scatter because it gives a slightly "disintegrated" look to a picture as pixels are moved around - one pixel could potentially get swapped all the way to the other side of the screen, although it isn't likely!
The scatter algorithm works like this:
-
Go through each pixel
-
Get a random X value between some negative number and some positive number
-
Get a random Y value between some negative number and some positive number
-
If the values are over the width/height of the image or under 0, continue the loop with the next pixel
-
Otherwise, get the colour from the current pixel
-
Get the colour from the nearby pixel
-
Swap the two.
In PHP it is barely more difficult:
function scatter(&$image) {
$imagex = imagesx($image);
$imagey = imagesy($image);
for ($x = 0; $x < $imagex; ++$x) {
for ($y = 0; $y < $imagey; ++$y) {
$distx = rand(-4, 4);
$disty = rand(-4, 4);
if ($x + $distx >= $imagex) continue;
if ($x + $distx < 0) continue;
if ($y + $disty >= $imagey) continue;
if ($y + $disty < 0) continue;
$oldcol = imagecolorat($image, $x, $y);
$newcol = imagecolorat($image, $x + $distx, $y + $disty);
imagesetpixel($image, $x, $y, $newcol);
imagesetpixel($image, $x + $distx, $y + $disty, $oldcol);
}
}
}
To make your pixels scatter further, change the two values inside the rand() call.

|
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!
|