Gen X Design | Ian Selby

All Things Web 2.0

PHP Thumbnailer Class v2.0

Overview

A PHP image manipulation class, aimed at generating thumbnails. It features the ability to resize by width, height, and percentage, create custom crops, or square crops from the center, rotate the image, and create Apple™-style reflections. It also features the ability to perform multiple manipulations per instance (also known as chaining), without the need to save and re-initialize the class with every manipulation.

This class comes in both PHP 4 and 5 flavors, but I highly recommend the PHP 5 version, due to the “__destruct()” function that became available in version 5. This helps ensure that you do not inadvertently create memory leaks by forgetting to call the “destruct()” function explicitly, like you must in the PHP 4 version of this script.

What’s New?

After the large amount of feedback that I got with the first version of this class, I did a lot of code refactoring, and simplified the API greatly. I have also added some new features:

  • You can now create custom crops, as well as square crops from the center of the image
  • You can also rotate the image clock-wise or counter clock-wise in 90° increments
  • You can now create those fancy Apple™-style reflections that are all the rage with the cool “web 2.0″ kids!

For the uninitiated, the class still contains it’s old features:

  • Works with gif,jpg, and png images
  • Ability to resize by percentage, width, or height
  • Ability to set quality of jpg images (0-100%)
  • Ability to perform multiple manipulations and saves without re-initializing class, or reloading original image
  • Ability to display manipulated image on the fly, enabling dynamic image generation in your scripts

Downloads & Demo

 Both PHP 5 & 4 Versions
 Download PHP 4 v2.0
 Download PHP 5 v2.0

Demo:
A demo of the script can be found here.

Usage

To begin, you need to create an instance of the class:

<?php
include_once('thumbnail.inc.php');
$thumb = new Thumbnail('path/to/image/file.jpg');
?>

Now you can begin your manipulations. The individual functions are described in detail below.

IMPORTANT PHP 4 NOTE
You must remember to call the destruct() function at then end of your scripts in order to deallocate the memory used for the image manipulation, similar to the way you must always call fclose() when you use fopen(). The PHP 5 class does this automatically, so there is no need to explicitly call this function (it doesn’t exist as a matter of fact!).

The API

resize($maxWidth,$maxHeight)
Resizes the image to be now wider than maxWidth and no higher than maxHeight. Both values are required. Example:

//resize image to no wider than 250 pixels wide and 250 pixels high
$thumb->resize(250,250);

resizePercent($percent)
Resizes the image to a percentage of its original size. Example:

//reduce the image by 50%
$thumb->resizePercent(50);

cropFromCenter($cropSize)
Create a square crop of $cropSize pixels from the center of the image. Example:

//create a 100x100 pixel crop from the center of an image
$thumb->cropFromCenter(100);

crop($startX,$startY,$width,$height)
Crop the image at $startX,$startY with a crop area of $width by $height pixels. Example:

//create a 100x50 pixel crop from the top left corner of an image
$thumb->crop(0,0,100,50);

rotateImage($direction)
Rotates the image 90° either clock-wise (default) or counter clock-wise. Example:

//rotate the image clock-wise
$thumb->rotateImage();  //also valid: $thumb->rotateImage('CW');
//rotate the image counter clock-wise
$thumb->rotateImage('CCW');

createReflection($percent,$reflection,$white,$border,$borderColor)
Creates an Apple™-style reflection (it’s more of a web 2.0 thing now, I know…) from an image. This one’s a bit weird to explain, but here goes:

  • $percent - What percentage of the image to create the reflection from
  • $reflection - What percentage of the image height should the reflection height be. i.e. If your image is 100 pixels high, and you set reflection to 40, the reflection would be 40 pixels high.
  • $white - How transparent (using white as the background) the reflection should be, as a percent
  • $border - Whether a border should be drawn around the original image (default is true)
  • $borderColor - The hex value of the color you would like your border to be (default is #a4a4a4)

Here’s an example:

And the code that generated it:

$thumb->createReflection(40,40,80,true,'#a4a4a4');

License

This library is licensed under the MIT License. You can use it for whatever you?d like, as long as the copyright notices remain in place.

Feel free to submit any comments, or bugs below

15 Responses for "PHP Thumbnailer Class v2.0"

  1. PHP Thumbnailer Class - CodeIgniter at katodivaihe PHP Thumbnailer Class - CodeIgniter at katodivaihe April 10th, 2008 at 6:24 am 1

    […] üzerinde bir çok işlemi rahatlıkla yapacabileceğiniz bu kütüphaneyi kullanmakta çok kolay. Thumbnailer Class ile image dosyalarınızı farklı şekillerde yeniden boyutlandırabilir, kesme işlemleri […]

  2. Stefan Stefan April 16th, 2008 at 7:10 am 2

    Hey guy, really GREAT script! Iam using it in 2 projects :-)) please keep on making it better ;-).

  3. fusion fusion April 16th, 2008 at 11:58 pm 3

    great job dude, also i see the php5 class and is very cool caz u use __construct and __destruct very nice dude, can i help in anything?

    maybe i can be a mirro for ur phpthumb files, just le me know if i can help dude.

  4. Martin Bean Martin Bean April 17th, 2008 at 1:49 am 4

    Hi, this PHP class is awesome.

    I’m building a bespoke content management system and this has really taken the hassle out of creating thumbnails and maximum-sized images for my photo gallery module; it does everything I need.

    Congratulations on producing something so, so simple and easy to use for something that’s so boring and meticulous.

  5. Karl Roos Karl Roos April 18th, 2008 at 1:33 pm 5

    Is it possible to save the generated image?

  6. Ian Ian April 19th, 2008 at 9:50 am 6

    @Karl,

    It’s totally possible, check out the class itself, you can use the save method:

    $thumb->save(’/path/to/the/fileyouwanttosave.jpg’);

  7. Evgeny Evgeny April 22nd, 2008 at 6:22 am 7

    Thanks! Very usefull class! I like it! But if GIF have transparency, background became black. How to make it white? Thanks!

  8. stef stef April 22nd, 2008 at 8:22 am 8

    sorry..i have used your class..but i have a problem:

    �PNG  ��� IHDR����������’���� PLTE����������^������IDAT8��A �0 ES!���;�9E\��`�#.=E���*: ��r����o�����¢M����9���p�Ќ�� G5�Ә�b����8 �G�^���%��f���cD�4�9�ۮ� 6Ӽ��2′g��p��z9ݓ�\R���?�^�G�^|߶�^iޣ_���+n��3�����IEND�B`�
    Fatal error: Cannot break/continue 1 level in /membri2/nephilimdie/asa/form/php/class/thumbnail.inc.php on line 173

    do you know this?what is it?

    thanks to help me!

  9. Franck Pascal Franck Pascal April 24th, 2008 at 4:46 am 9

    It could be sweet if we can apply watermarks or images overlay. What do you think?

  10. Killer.net Killer.net April 28th, 2008 at 12:33 pm 10

    This class y very usefull to us who develop aplicattions in flash with php, because make our life so much easy with the managment of images.

    Thanks and congratulations.

  11. Milder Lisondra Milder Lisondra May 2nd, 2008 at 9:51 am 11

    I get the following error when uploading GIF images.

    Fatal error: Call to undefined function: imagegif() in /home/cust1/user1376116/html/dtools/classes/thumbnail.inc.php on line

    Its weird because I checked the actual class and its happening within this function (”show”):

    function show($quality=100,$name = ”) {
    switch($this->format) {
    case ‘GIF’:
    if($name != ”) {
    ImageGif($this->newImage,$name);
    }
    else {
    header(’Content-type: image/gif’);
    ImageGif($this->newImage);
    }
    break;
    case ‘JPG’:
    if($name != ”) {
    ImageJpeg($this->newImage,$name,$quality);
    }
    else {
    header(’Content-type: image/jpeg’);
    ImageJpeg($this->newImage,”,$quality);
    }
    break;
    case ‘PNG’:
    if($name != ”) {
    ImagePng($this->newImage,$name);
    }
    else {
    header(’Content-type: image/png’);
    ImagePng($this->newImage);
    }
    break;
    }
    }

    Help anyone?

  12. danster danster May 6th, 2008 at 4:06 am 12

    HI, Im using phpmaker and was told this is an extension for it. I cant get this working at all and cant find any documentation for adding an extension to phpmaker. can anyone tell how to add it to my extensions list within phpmaker? thanks.

  13. Me Me May 6th, 2008 at 3:41 pm 13

    danster, this isn’t an extension - you just need to use it as an include file. In the download you’ll see an example - take a look.

  14. Javier Javier May 7th, 2008 at 12:25 pm 14

    Here is a watermarking code requested above i needed it too:

    Add BEFORE last curly bracket(})
    ++++++++++
    public function watermark($imagesource){
    $pathinfo = pathinfo($imagesource);
    $var1 = $pathinfo[’extension’];
    $var2 = “png”;
    $var3 = “jpeg”;
    $var4 = “jpg”;
    $var5 = “gif”;
    if(strcasecmp($var1, $var2) == 0){
    $watermark = @imagecreatefrompng($imagesource);
    }elseif((strcasecmp($var1, $var3) == 0) || (strcasecmp($var1, $var4) == 0)){
    $watermark = @imagecreatefromjpeg($imagesource);
    }elseif(strcasecmp($var1, $var5) == 0){
    $watermark = @imagecreatefromgif($imagesource);
    }
    $watermarkwidth = imagesx($watermark);
    $watermarkheight = imagesy($watermark);
    $startwidth = ($this->currentDimensions[’width’] - $watermarkwidth);
    $startheight = ($this->currentDimensions[’height’] - $watermarkheight);
    imagecopy($this->workingImage, $watermark, $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
    }
    ++++++++++

    USAGE
    ++++++++++
    $thumb = new Thumbnail(”image/to/watermark.jpg”);
    $thumb->resize(360,355);
    $thumb->watermark(”path/to/watermark.png”);
    $thumb->show();
    ++++++++++
    all image file type accepted except bmp of coarse

  15. Peter Peter May 9th, 2008 at 1:06 am 15

    Awesom - thanks a lot, Ian!


Leave a reply


PhotoStream

    I Have Altered the PoolGriffin Cleanses his Palette... sometimes I can't be bothered to wait for him to walk fasterMore fun in the Peace FountainWatching the Birds (I think)Loving MommyPlaying in the Peace FountainKids + Water = Endless FunOMG WATER!

Asides

Categories

About Me

Gen X Design has been my freelance development and design company for some time now, and my services are sometimes available.

Recently, I've been too wrapped up in work to pursue my own interests. To that end, I've made some changes in my life, re-worked this site so I'm happy with it again, and have decided to get back to writing and developing.

I have a passion for all things Web 2.0, love shiny icons and gradients, and live in the San Francisco Bay area. I work for Aptana.