Pixelate Images With PHP
The other day I needed to hide an image but keep the original image intact so rather than do complicated things with light and dark filters I decided the best way would be to pixelate the image. All that is required to pixelate an image is to shrink it down and then blow it up to the original size, thus reducing the quality of the image.
The following code will do this process for a jpeg image. The pixelate amount variable is used to reduce the width and height of the first image using division and then multiply them back again to the original values for the output image. Remember to change the ImageCreateFromJPEG() to the format you want.
$imgfile = 'mushrooms.jpg';
$image = ImageCreateFromJPEG($imgfile);
$imagex = imagesx($image);
$imagey = imagesy($image);
// Amount to pixelate
$pixelate_amount = 10;
# Create version of the original image:
$tmpImage = ImageCreateTrueColor($imagex, $imagey);
imagecopyresized($tmpImage, $image, 0, 0, 0, 0, round($imagex / $pixelate_amount), round($imagey / $pixelate_amount), $imagex, $imagey);
# Create 100% version ... blow it back up to it's initial size:
$pixelated = ImageCreateTrueColor($imagex, $imagey);
imagecopyresized($pixelated, $tmpImage, 0, 0, 0, 0, $imagex, $imagey, round($imagex / $pixelate_amount), round($imagey / $pixelate_amount));
header("Content-Type: image/JPEG");
imageJPEG($pixelated, "", 75);
This will take the following image:
And change it into this:
I took the ImageManipulation PHP class that I have written previously and modified it to include a function called setPixelate(). This function takes a single parameter, which is the amount of pixelation to apply to the image.
The createResampledImage() image was tweaked slightly to include the code that reduces and then restores the image. The $tmpImage variable is used to store the reduced image.
The following code is used to pixelate the image and print it out using the ImageManipulation class. If you want to save the image instead then use the save() function with the optional parameter of the filename that the image will be saved as.
require('ImageManipulation.php');
$src = 'mushrooms.jpg';
$objImage = new ImageManipulation($src);
if ( $objImage->imageok ) {
$objImage->setPixelate(10);
$objImage->show();
}
Comments
Post new comment