Pixelate Images With PHP

3rd June 2009 - 2 minutes read time

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:

Image of mushrooms, non pixelated

And change it into this:

Image of mushrooms, pixelated

Add new comment

The content of this field is kept private and will not be shown publicly.