Creating Pixelated / Mosaic images with GD in PHP

Posted on January 1, 2008. Filed under: GD, PHP | Tags: , , , , |

A simple way to create a pixelated [or mosaic-looking] image in PHP using GD is to, in theory:

  1. Create a image resource for the soon-to-be-pixelated image
  2. Resize the image to 5% of it’s original size [adjust to taste]
  3. Save image to server or send to browser

Using the script below will turn the image on the left into the images on the right …
Pixelated Example
Photo by pinklimoncello.

The left-most image is at 0% pixelation [and is the original image]. The middle middle image is at 5%, and right right-most image is at 20% pixelation.

Have at it!


<?php
    $img = imagecreatefromjpeg("image.jpg");
    $width = imagesx($img);
    $height = imagesy($img);

    # Create 5% version of the original image:
    $newImg = imagecreatetruecolor($width,$height);
    imagecopyresized($newImg,$img,0,0,0,0,round($width / 5),round($height / 5),$width,$height);

    # Create 100% version ... blow it back up to it's initial size:
    $newImg2 = imagecreatetruecolor($width,$height);
    imagecopyresized($newImg2,$newImg,0,0,0,0,$width,$height,round($width / 5),round($height / 5));

    # No need for a jpeg here :-)
    imagepng($newImg2,"imagePixelated.png");
?>

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: