I put together a simple, lightweight PHP class for generating thumbnail images. The class is compatible with PHP5 and uses the GD2 extension (included by default with PHP5) to create JPEG, PNG, and GIF thumbnails. I’ve setup a Google Code project for it: Gregphoto_Image where you can checkout the source from SVN and file bugs.

The class has the following basic features:

  • Ability to read JPEG, PNG, or GIF images
  • Ability to output JPEG, PNG, or GIF images
  • 4 modes of thumbnail creation
    • MAX_HEIGHT – you specify a maximum height and the dimensions are calculated based off of the height
    • MAX_WIDTH – you specify a maximum width and the dimensions are calculated based off of the width
    • BEST_FIT – you specify a maximum height and width and the dimensions are calculated so that the thumbnail
      is as large as possible without exceeding the maximum height or width
    • EXACT – you specify a maximum height and width and these are directly used. Causes distortion if the
      chosen aspect ratio is different from the aspect ratio of the image
  • Renders/saves images in their input format by default, but allows changing the format. For example, input a GIF but output a PNG
  • Fully documented object oriented code
  • Fluent interface for creating thumbnails with a minimal amount of code

The class is licensed under the MIT license, which basically means it can be used and modified by anyone – for personal or commercial use.

You can Download it from the project page on Google Code. You can view examples of it running on my site – the examples are checked into SVN and can be viewed on the project site. You can also view the docs.

Example usage:

1
2
3
4
5
6
7
require('path/to/Gregphoto_Image.php');
$image = new Gregphoto_Image('path/to/sample/image.jpg');
$image->setMaxHeight(200);
$image->setMaxWidth(200);
$image->setJpegQuality(90);
$image->resize(Gregphoto_Image::BEST_FIT);
$image->showThumbnail();
1
2
$image = new Gregphoto_Image('../images/fan.jpg');
$image->setMaxHeight(200)->setJpegQuality(90)->resize()->showThumbnail();
1
2
3
4
5
6
7
8
require('path/to/Gregphoto_Image.php');
$image = new Gregphoto_Image('path/to/image.jpg');
$image->setMaxHeight(200);
$image->setMaxWidth(200);
$image->setJpegQuality(90);
$image->setOutputType(IMAGETYPE_PNG);
$image->resize(Gregphoto_Image::BEST_FIT);
$image->saveThumbnail('path/to/thumbnail.png');

Enjoy!