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.

Click here to lend your support to: Gen X Design Thumbnailer Support and make a donation at www.pledgie.com !

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.

Click here to lend your support to: Gen X Design Thumbnailer Support and make a donation at www.pledgie.com !

Feel free to submit any comments, or bugs below

52 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!

  16. Regor Regor May 19th, 2008 at 1:34 am 16

    Hi there! First of all awesome script! It’s beautifully written and clearly explained.

    On second hand I am having some trouble displaying two or more thumbnails at a time. How should I do that? I try calling two times by using changing the filename, but both images are not different. weird -_-U

    The resulting images seem to be renamed the same .. in the example provided is ’show_image.php.jpg.jpg’.

    Is there a way to provide a custom name here like thumb1.jpg for instance?

  17. Regor Regor May 19th, 2008 at 2:52 am 17

    Hi again.

    Just to say that there is actually no issue with this. I don’t know why I wasn’t able to show different thumbnails and every image looked the same.. (maybe some cache issue). So everything works as expected.

  18. deep deep May 21st, 2008 at 11:38 am 18

    hi i am getting error file not found.

  19. Mike Mike May 23rd, 2008 at 6:44 am 19

    Hello,

    Thank you for sharing your hard work.
    Strangely, the download of a zip containing both versions worked fine;
    but the download of just version 5 did not work for me.
    99.9999% sure it is my fault in some way but worth mentioning just in case.

  20. Mike Mike May 23rd, 2008 at 8:04 am 20

    What I really want to do is to save the file;
    my attempt to do this failed and then I noticed that the example script was not working. Cleared cache. Still not getting results I would expect. So I will leave this script for now. Probably just me.

  21. @AWhim @AWhim June 1st, 2008 at 9:40 pm 21

    This script is waaaay easy to use. For calling images to be clearly resized and cropped, it does a great job … especially with its flexibility … really suits my need to display different thumb types, image sizes depending on where they are to be displayed on the site. Top job.

  22. stormy stormy June 6th, 2008 at 6:40 am 22

    Hey Ian,
    first of all. A great script!
    What also will be great, if adding watermarks to thumbs will be integrated. for example a little zoom icon in the right corner.
    think thats often an issue when generating thumbnails.

  23. Tony Tony June 6th, 2008 at 8:45 am 23

    Hi, great work.
    Just a question, how can I show the new dimension (width & height) of the picture after resize it ?

  24. Will Will June 10th, 2008 at 6:03 pm 24

    I’ve had great success with this class- thanks so much. It’s a live saver.

    However, I’ve recently tried to undertake a project that requires creating (and saving) varying sized versions of 24-bit transparent PNG source images. I’m able to create and save the files, but the transparency seems to be lost in the process, with the background being filled in with black in the final image.

    Is the class fundamentally incompatible with transparent PNGs, or am I simply doing something wrong.

    Thanks!

  25. Scott Scott June 14th, 2008 at 9:40 am 25

    I too get the following error:

    �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`�

  26. Damian Casale Damian Casale June 14th, 2008 at 5:37 pm 26

    Hi guys, I hope I can help you out a bit.

    I’m trying out the class myself and It wasn’t working directly from uploaded files. I have looked into the script and it appears to do a simple file type check based on the file extension, which for an uploaded file (in *nix anyhow) is a generated string with no file extension.

    So we could rename the file before passing it into the script with the rename(); function

    or

    We can rewrite the thumbnail construct to include file type checking via either :

    the PECL file info functions http://es.php.net/manual/en/function.finfo-file.php

    or (if you don’t have access to PECL)

    the deprecated mime_content_type (); function. http://es.php.net/manual/en/function.mime-content-type.php

  27. Damian Casale Damian Casale June 14th, 2008 at 5:47 pm 27

    As my client does not have access to PECL I have changed the constructor to use the mime_content_type () function.

    //if there are no errors, determine the file format

    if($this->error == false) {
    switch ( mime_content_type ( $this->fileName ) ) {
    case ‘image/gif’:
    $this->format = ‘GIF’;
    break;
    case ‘image/png’:
    $this->format = ‘PNG’;
    break;
    case ‘image/jpg’:
    case ‘image/jpeg’:
    $this->format = ‘JPG’;
    break;
    default:
    $this->errmsg = ‘Unknown file format’;

    $this->error = true;
    break;
    }

    }

  28. jorko jorko June 17th, 2008 at 1:32 am 28

    Is it possible to resize only with given Width?
    For example, you set something like that:
    $thumb->resize_width(125);
    and it resize the width to 125, and the height with the same ratio as (new width, old width).

  29. jorko jorko June 17th, 2008 at 1:45 am 29

    ohh, I thought that it didn`t resize with ratio, but it does !

    This is the best class I`ve ever seen. Great work man !

    Will you put some light to this ability:
    + Ability to resize by percentage, width, or height
    How to put a percentage ?

  30. Kamera Kamera June 18th, 2008 at 12:48 am 30

    Great script - and thank you for the hard work!

    I was just wondering how to save if the path to file and the filename is called is a $string variable?

    $thumb->save(’images/thumbnails/$thumb’); will create a file called $thumb and not the name of the original file :-(

    If I use a $dirName then it will not save anywhere as it can not find a direcotory name called $dirName.

  31. jorko jorko June 18th, 2008 at 11:02 pm 31

    $thumb->save(’images/thumbnails/’.$thumb);

    or

    $path=’images/thumbnails/’.$thumb;
    $thumb->save($path);

  32. sfx sfx June 21st, 2008 at 3:00 pm 32

    I have a problem with some jpg images, when i`m upload image on local mashine (apache, winXP) there are uploading succesufull, when i upload image (JPG) on public server (LINUX, Apache), they just don`t upload without errors and other JPG ok. GD versions is same.

  33. Zia Zia June 23rd, 2008 at 4:01 am 33

    I have downloaded it but i am unable to play demo.
    can any one help me?

  34. Kamera Kamera June 23rd, 2008 at 6:06 am 34

    I am trying to get a thumb to save with a $string

    this one works - I did it to make sure that I have the path right :)

    $thumb->save(”thumbnails/myfile.jpg”); // this works

    None of the following work
    $thumb->save(’thumbnails/’.$thumb);

    or
    $path=”thumbnails/$thumb”;
    $thumb->save($path);

    or
    $path=’thumbnails/’.$thumb;
    $thumb->save($path);

    or
    $thumb->save(”thumbnails/$thumb”);

    or
    $thumb->save(’thumbnails/’.$thumb);

    Could someone kindly tell me where I am gong wrong?
    Thank you for your time.

  35. Jim Byrne Jim Byrne June 26th, 2008 at 6:01 am 35

    What settings do I need to ensure that my resized image is always 150 pixels wide - with the height resized proportionally. Currently if I use $thumb->resize(150,150); I get the height that is 150pixels and the width smaller than I want. This is because the height is always bigger than the width on the original images.

    Thanks for the script. Much appreciated.

    All the best,
    Jim

  36. Thumbnails for PureEdit - 61924 Thumbnails for PureEdit - 61924 July 1st, 2008 at 4:29 am 36

    [...] download the thumbnail class I used here: http://www.gen-x-design.com/projects/php-thumbnailer-class/. I used the PHP5 version and I wrote this manual also for the PHP5 version. This class was the [...]

  37. Gerardo Gerardo July 2nd, 2008 at 11:47 am 37

    Hi, I’m trying to use it with an applicattion with Zend Framework, I’m getting the following error: File not found, and I can see through the navigation bar the File. Can anyone help me?
    By the way, I’m using an .htaccess file, is there any rule to apply?

    Regards

  38. Justin Justin July 2nd, 2008 at 2:31 pm 38

    @Kamera

    Look at your variable $thumb. You are trying to pass it an object of $thumb not a string variable. Try it with something different than $thumb. Try something like this:

    $imagename = ’somefile.jpg’;
    $thumb->save(’thumbnails/’.$imagename);

  39. A Little Man In The Big City » Blog Archive » PHP Thumbnailer Demo A Little Man In The Big City » Blog Archive » PHP Thumbnailer Demo July 2nd, 2008 at 11:47 pm 39

    [...] เข้าไปดูได้ที่นี่ ครับ http://www.gen-x-design.com/projects/php-thumbnailer-class/ อันนี้วิธีใช้อย่างละเอียด [...]

  40. karlos karlos July 3rd, 2008 at 12:35 am 40

    Hi , I’m trying to use this class with phpmaker , pls help me!

    Thanks

  41. Will Will July 3rd, 2008 at 2:09 pm 41

    Gerardo,

    I ran into a similar problem, typically when an uploaded file would fail to complete at some point during the upload. These “bad” files would then choke the thumbnailer class when it ran on them.

    I can’t offer a solution that will prevent the files from becoming corrupted, but I was able to use the following code to check and make sure that the .jpg file is in fact correctly formed before I attempt to thumbnail it (which I was doing via a chron job):

    ———-
    $f = fopen($tmpReadFile, ‘r’);
    $l = filesize($tmpReadFile);
    $soi = fread($f, 2);
    fseek($f, $l-2);
    $eoi = fread($f, 2);
    $soiMarker = unpack(”H*”,$soi);
    $eoiMarker = unpack(”H*”,$eoi);
    if (intval($soiMarker[1],16) == 0xFFD8 && intval($eoiMarker[1],16) == 0xFFD9){
    // file is good - proceed with thumbnailing
    }
    ———-

    In the above code, $tmpReadFile is the full path to the file on the server.

    Basically, the code above checks the beginning and the end of the file for opening and closing JPG markers. If they’re both there, that means the file starts and ends correctly and it’s (fairly) safe to assume it’s good. Not foolproof, but weeded out all of my corrupted files.

    I hope that helps.

  42. Shain Shain July 5th, 2008 at 6:34 am 42

    Thank you so much for putting this. This class is excellent and extremely easy to use.

  43. Kazakbala Kazakbala July 5th, 2008 at 11:43 am 43

    The best class for working with images.
    In future it could be return EXIF data from images )))

  44. Bas Bas July 11th, 2008 at 6:55 am 44

    Great class. I’ve used it to resize an image to 500px width and then make a perfect 100px * 100px thumbnail using the following code:

    //– upload image
    move_uploaded_file($_FILES['photoupload']['tmp_name'], $path . $filename);

    //– resize to 500px
    $thumb = new thumbnail($path . $filename);
    $thumb->resize(500);
    $thumb->save($path . $filename);
    $thumb->save($path . $thumb_filename);
    unset($thumb);

    //– create thumbnail
    $thumb = new thumbnail($path . $thumb_filename);
    if ($size[0] > $size[1])
    $thumb->resize(”, 100);
    else
    $thumb->resize(100, ”);
    $thumb->save($path . $thumb_filename);
    unset($thumb);

    //– crop thumbnail
    $thumb = new thumbnail($path . $thumb_filename);
    $thumb->cropFromCenter(100);
    $thumb->save($path . $thumb_filename);

  45. Simon66 Simon66 July 22nd, 2008 at 10:43 pm 45

    I smashed two functions together to create another; The Top Center Crop.
    Put this in your $thumb list:
    //create a 100×100 pixel crop from the top center
    $thumb->TopCenterCrop(0,100,100);

    And put this in the thumbnail.inc.php file after the crop function:
    /**
    * Advanced cropping function that crops an image using $centerX and $startY as the top-center.
    *
    * @param int $centerX
    * @param int $startY
    * @param int $width
    * @param int $height
    */
    public function TopCenterCrop($startY,$width,$height) {
    //make sure the cropped area is not greater than the size of the image
    if($width > $this->currentDimensions['width']) $width = $this->currentDimensions['width'];
    if($height > $this->currentDimensions['height']) $height = $this->currentDimensions['height'];
    //make sure not starting outside the image
    $centerX = intval(($this->currentDimensions['width'] - $width) / 2);
    if(($startY + $height) > $this->currentDimensions['height']) $startY = ($this->currentDimensions['height'] - $height);
    if($startY workingImage = ImageCreateTrueColor($width,$height);
    }
    else {
    $this->workingImage = ImageCreate($width,$height);
    }

    imagecopyresampled(
    $this->workingImage,
    $this->oldImage,
    0,
    0,
    $centerX,
    $startY,
    $width,
    $height,
    $width,
    $height
    );

    $this->oldImage = $this->workingImage;
    $this->newImage = $this->workingImage;
    $this->currentDimensions['width'] = $width;
    $this->currentDimensions['height'] = $height;
    }

    Seems to work for me.

  46. Senthil Senthil July 23rd, 2008 at 4:17 am 46

    Hi Ian,

    Its totally amazing…
    Thanks for your help…

  47. tronics tronics July 27th, 2008 at 10:09 am 47

    TopCenterCrop working.. had a few problems with your code..

    /**
    * Advanced cropping function that crops an image using $centerX and $startY as the top-center.
    *I smashed two functions together to create another; The Top Center Crop.
    Put this in your $thumb list:
    //create a 100×100 pixel crop from the top center
    $thumb->TopCenterCrop(0,100,100);

    And put this in the thumbnail.inc.php file after the crop function:
    * @param int $centerX
    * @param int $startY
    * @param int $width
    * @param int $height
    */
    public function TopCenterCrop($startY,$width,$height) {
    //make sure the cropped area is not greater than the size of the image
    if($width > $this->currentDimensions['width']) $width = $this->currentDimensions['width'];
    if($height > $this->currentDimensions['height']) $height = $this->currentDimensions['height'];

    //make sure not starting outside the image
    $centerX = intval(($this->currentDimensions['width'] - $width) / 2);

    if(($startY + $height) > $this->currentDimensions['height']) $startY = ($this->currentDimensions['height'] - $height);

    $this->workingImage = ImageCreateTrueColor($width,$height);

    imagecopyresampled(
    $this->workingImage,
    $this->oldImage,
    0,
    0,
    $centerX,
    $startY,
    $width,
    $height,
    $width,
    $height
    );

    $this->oldImage = $this->workingImage;
    $this->newImage = $this->workingImage;
    $this->currentDimensions['width'] = $width;
    $this->currentDimensions['height'] = $height;
    }

  48. tronics tronics July 27th, 2008 at 10:23 am 48

    Debugged Watermarkfunction:
    /*
    $thumb = new Thumbnail(”image/to/watermark.jpg”);
    $thumb->resize(360,355);
    $thumb->watermark(”Thumbnailtext”);
    $thumb->show();
    */
    public function WriteWatermark($watermarktext=”"){
    if ($watermarktext==”")
    $watermarktext=date(”d.m.Y H:i:s”,time());

    $pathinfo = pathinfo($this->fileName);
    //$imagewithwatermark = @imagecreatefromjpeg($this->fileName);

    $var1 = $pathinfo['extension'];
    $var2 = “png”;
    $var3 = “jpeg”;
    $var4 = “jpg”;
    $var5 = “gif”;

    if(strcasecmp($var1, $var2) == 0){
    $imagewithwatermark = @imagecreatefrompng($this->fileName);
    }elseif((strcasecmp($var1, $var3) == 0) || (strcasecmp($var1, $var4) == 0)){
    $imagewithwatermark = @imagecreatefromjpeg($this->fileName);
    }elseif(strcasecmp($var1, $var5) == 0){
    $imagewithwatermark = @imagecreatefromgif($this->fileName);
    }
    if (!$imagewithwatermark) {
    die (’not working watermark’);
    }
    //http://apniphp.blogspot.com/2008/05/put-watermark-on-images-using-php.html

    $black = imagecolorallocate($imagewithwatermark, 0, 0, 0);
    $font = ‘arial.ttf’;
    $font_size = 10;
    //imagettftext($imagewithwatermark, $font_size, 0, 10, 20, $black, $font, $watermarktext);

    $tb = imagettfbbox($font_size, 0, $font, $watermarktext);

    /*
    This’ll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
    Array
    (
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
    )
    */

    $watermarkwidth = imagesx($imagewithwatermark);
    $watermarkheight = imagesy($imagewithwatermark);
    $startwidth = ($this->currentDimensions[’width’] - $watermarkwidth);
    $startheight = ($this->currentDimensions[’height’] - $watermarkheight);

    $x = ceil(($startwidth - $tb[2]) / 2); // lower left X coordinate for text
    imagettftext($imagewithwatermark, $font_size, 0, 2, 11, $black, $font, $watermarktext);

    $this->newImage=$imagewithwatermark;

    //imagecopy($this->workingImage, $imagewithwatermark, $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
    imagecopy($this->workingImage,$this->newImage, $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
    }

  49. isnain isnain July 31st, 2008 at 10:03 pm 49

    can this script make an image transparent?

  50. Edwin Steenwinkel Edwin Steenwinkel August 5th, 2008 at 2:13 pm 50

    Do you got a black background, on your transparent PNG. Me 2… but I have the solution:

    Add this code to row 319 in thumbnail.inc.php above ‘ImageCopyResampled(’:

    if( $this->format == ‘PNG’ ) {
    imagealphablending($this->workingImage, false);
    $colorTransparent = imagecolorallocatealpha($this->workingImage, 0, 0, 0, 127);
    imagefill($this->workingImage, 0, 0, $colorTransparent);
    imagesavealpha($this->workingImage, true);
    }

    Good luck!

  51. +ve +ve August 5th, 2008 at 9:37 pm 51

    I have been trying to include the php codes that you offered into my website
    resize(250,250);
    $thumb->show();

    ?>
    but immediately I include another code or try to include it on another page so that it resizes the pictures and position them where i want it, it gives me an error message(THIS IS THE ERROR ON MOZILLA FIREFOX http://localhost/thumbnailer/) THE CODES THAT I INCLUDED WAS JUST A DIV resize(250,250);
    $thumb->show();

    ?>

  52. Deezaz Deezaz August 6th, 2008 at 5:39 am 52

    where do i get the ‘thumbnail.inc.php’ file? that you hae required in the thnb nail code??


Leave a reply


See Me @ AjaxWorld '08 West

AJAX RIA - Server-Side JavaScript - All the Cool Kids Are Doing It!

PhotoStream

    Griffin Playing in Alamo SquareThe Painted Ladies, and the City in the BackgroundThe Painted LadiesMore Golden Gate Bridge GoodnessAlcatraz IslandThe Golden GateGive Mommy KissMommy & Griffin Playing at Crissy FieldDaddy and Griffin Leaving Crissy Field

Asides

  • Firebug Lite 1.2 Released

    If you've ever used Firebug for JS development, you know how indisposable it is. If you haven't, you're insane, and you need to start using it now! Firebug Lite was created to be able to embed a more limited version of the library in non-firefox browsers. Previously, you couldn't do much with it outside of the console. functions and use a JS command-line. Looks like that's a thing of the past with the new release. It's pretty much as functional as the actual Firefox extension, and is well worth checking out:
    Firebug Lite 1.2 Released (via Ajaxian)

  • BgPatterns.com - Cool Background Image Generator

    While its generally not my style, I would have loved to have something like this several times in the past. Slick, easy, classy, fun, and actually worthwhile. Check it out:
    www.bgpatterns.com

  • savethedevlopers.org - Save a Developer. Upgrade Your Browser

    "Say No To IE 6!
    Our current campaign focuses on assisting users in upgrading their Internet Explorer 6 web browser. This campaign will result in former IE 6 users having a more enjoyable experience on the web while (hopefully) creating a less stressful and complicated environment for web developers by hastening the retirement of an outdated browser."

    http://www.savethedevelopers.org/

  • Evernote - Awesome Note Capturing Software

    I know, yet another note capture / organize program... but this one's different. It's got really powerful OCR software (it will pull text from images, even handwriting) that automatically finds words in your images and indexes them, making it easier to find later. Works on the web, your mobile phone, and PC or Mac. Best of all, it's free!
    Evernote - Capture. Sync. Find

  • Magic Toolbox - High Quality JS Tools

    Nice little suite of JS tools... they're commercial, but reasonably priced. The names kinda imply what they do: Magic Zoom, Magnify, and Thumbs. Definitely worth a look:
    Magic Toolbox

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.