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 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, Pixelate >>
Previous chapter: Special FX, Noise
Jump to:
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.