All Things Web 2.0
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.
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:
For the uninitiated, the class still contains it’s old features:
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.
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!).
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:
Here’s an example:
And the code that generated it:
$thumb->createReflection(40,40,80,true,'#a4a4a4');
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
52 Responses for "PHP Thumbnailer Class v2.0"
[...] ü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 [...]
Hey guy, really GREAT script! Iam using it in 2 projects :-)) please keep on making it better ;-).
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.
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.
Is it possible to save the generated image?
@Karl,
It’s totally possible, check out the class itself, you can use the save method:
$thumb->save(’/path/to/the/fileyouwanttosave.jpg’);
Thanks! Very usefull class! I like it! But if GIF have transparency, background became black. How to make it white? Thanks!
sorry..i have used your class..but i have a problem:
�PNG ��� IHDR����������’���� PLTE����������^������IDAT8��A �0ES!���;�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!
It could be sweet if we can apply watermarks or images overlay. What do you think?
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.
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?
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.
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.
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
Awesom - thanks a lot, Ian!
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?
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.
hi i am getting error file not found.
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.
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.
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.
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.
Hi, great work.
Just a question, how can I show the new dimension (width & height) of the picture after resize it ?
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!
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`�
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
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;
}
}
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).
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 ?
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.
$thumb->save(’images/thumbnails/’.$thumb);
or
$path=’images/thumbnails/’.$thumb;
$thumb->save($path);
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.
I have downloaded it but i am unable to play demo.
can any one help me?
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.
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
[...] 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 [...]
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
@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);
[...] เข้าไปดูได้ที่นี่ ครับ http://www.gen-x-design.com/projects/php-thumbnailer-class/ อันนี้วิธีใช้อย่างละเอียด [...]
Hi , I’m trying to use this class with phpmaker , pls help me!
Thanks
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.
Thank you so much for putting this. This class is excellent and extremely easy to use.
The best class for working with images.
In future it could be return EXIF data from images )))
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);
—
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.
Hi Ian,
Its totally amazing…
Thanks for your help…
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;
}
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);
}
can this script make an image transparent?
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!
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();
?>
where do i get the ‘thumbnail.inc.php’ file? that you hae required in the thnb nail code??
Leave a reply