PHP Thumbnailer Class v2.0
This Project has Moved!
I’ve finally got the next version of the class released, and it’s now got its own website! Check out the new hotness over at: http://phpthumb.gxdlabs.com
I’ve finally got the next version of the class released, and it’s now got its own website! Check out the new hotness over at: http://phpthumb.gxdlabs.com
Welcome to Gen X Design. The name’s a little corny, I know, but it’s one of those things I’ve used since I was a kid.
Anyway, I built this site for me (and some friends) to share their thoughts and ideas. I love all things web 2.0, shiny icons, and gradients. I live in the San Francisco Bay area, work for eMeter, and am sometimes available for contract work.
Mozilla announced a new feature for add-ons today: collections. It also looks like they’re getting the ball rolling with several useful collections, such as the Web Developer Collection. It includes all sorts of goodness like Firebug, ySlow, GreaseMonkey, ColorZilla, and many more. Well worth a quick visit.
FireFox Web Developer Collection
David Walsh has put together a really handy plugin for MooTools called ScrollSpy. What impressed me the most was the automatic display of a “Return to Top” link on your page once you’ve scrolled beyond a certain boundary. There are also a handful of other neat demos worth checking out. Sounds simple, but if you think about it, there are tons of great applications for this plugin.
http://davidwalsh.name/scrollspy
It’s been said a thousand times I’m sure, but picking the right JavaScript framework is a pain. There are all sorts of biased arguments for one vs. another, but there’s really nothing subjective out there… until now. Arguably, jQuery is probably the most popular JS framework out in the wild, but that doesn’t always mean it’s the best choice. What you choose should really depend on what you’re trying to do. Aaron Newton of Clientcide has put together a really impressive look at jQuery vs. MooTools, which doesn’t categorically say one is better than the other, but, rather, goes into detail about why one framework is better than the other based on your needs. Definitely worth a read:
www.jqueryvsmootools.com
ORM is certainly a very popular concept these days, but I haven’t really come across any PHP implementations that I found worth-while. Sure, big frameworks like CakePHP may have ORM functionality, but I’m not a fan of huge frameworks. I’ve also dabbled in my own implementations, but never got too far, as I’m not a fan of re-inventing the wheel. At any rate, I stumbled across Doctrine by accident (good ol’ RSS readers), and am impressed, mostly because it’s something that can be integrated into existing projects / frameworks.
www.doctrine-project.org
Ajaxload.info used to be the site of choice when it came to generating preloader images… unfortunately, I think it’s been bested. Preloaders.net allows you to generate not only the standard set of preloaders, but even 3D ones! You also get much more control (size, speed, etc.) and the quality of the final images is impressive. Definitely worth checking out.
www.preloaders.net
Use my projects, or just plain like what I do and what I write about?
Want to show your appreciation in a small way? I love coffee, why not buy me a cup now?
Apr 10 '08 at 6:24 am
[...] ü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 [...]
Stefan
Apr 16 '08 at 7:10 am
Hey guy, really GREAT script! Iam using it in 2 projects
) please keep on making it better
.
fusion
Apr 16 '08 at 11:58 pm
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.
Martin Bean
Apr 17 '08 at 1:49 am
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.
Karl Roos
Apr 18 '08 at 1:33 pm
Is it possible to save the generated image?
Ian
Apr 19 '08 at 9:50 am
@Karl,
It’s totally possible, check out the class itself, you can use the save method:
$thumb->save(’/path/to/the/fileyouwanttosave.jpg’);
Evgeny
Apr 22 '08 at 6:22 am
Thanks! Very usefull class! I like it! But if GIF have transparency, background became black. How to make it white? Thanks!
stef
Apr 22 '08 at 8:22 am
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!
Franck Pascal
Apr 24 '08 at 4:46 am
It could be sweet if we can apply watermarks or images overlay. What do you think?
Killer.net
Apr 28 '08 at 12:33 pm
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.
Milder Lisondra
May 2 '08 at 9:51 am
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?
danster
May 6 '08 at 4:06 am
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.
Me
May 6 '08 at 3:41 pm
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.
Javier
May 7 '08 at 12:25 pm
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
Peter
May 9 '08 at 1:06 am
Awesom – thanks a lot, Ian!
Regor
May 19 '08 at 1:34 am
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?
Regor
May 19 '08 at 2:52 am
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.
deep
May 21 '08 at 11:38 am
hi i am getting error file not found.
Mike
May 23 '08 at 6:44 am
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.
Mike
May 23 '08 at 8:04 am
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.
@AWhim
Jun 1 '08 at 9:40 pm
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.
stormy
Jun 6 '08 at 6:40 am
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.
Tony
Jun 6 '08 at 8:45 am
Hi, great work.
Just a question, how can I show the new dimension (width & height) of the picture after resize it ?
Will
Jun 10 '08 at 6:03 pm
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!
Scott
Jun 14 '08 at 9:40 am
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`�
Damian Casale
Jun 14 '08 at 5:37 pm
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
Damian Casale
Jun 14 '08 at 5:47 pm
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;
}
}
jorko
Jun 17 '08 at 1:32 am
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).
jorko
Jun 17 '08 at 1:45 am
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 ?
Kamera
Jun 18 '08 at 12:48 am
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.
jorko
Jun 18 '08 at 11:02 pm
$thumb->save(’images/thumbnails/’.$thumb);
or
$path=’images/thumbnails/’.$thumb;
$thumb->save($path);
sfx
Jun 21 '08 at 3:00 pm
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.
Zia
Jun 23 '08 at 4:01 am
I have downloaded it but i am unable to play demo.
can any one help me?
Kamera
Jun 23 '08 at 6:06 am
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.
Jim Byrne
Jun 26 '08 at 6:01 am
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
Jul 1 '08 at 4:29 am
[...] 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 [...]
Gerardo
Jul 2 '08 at 11:47 am
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
Justin
Jul 2 '08 at 2:31 pm
@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);
Jul 2 '08 at 11:47 pm
[...] เข้าไปดูได้ที่นี่ ครับ http://www.gen-x-design.com/projects/php-thumbnailer-class/ อันนี้วิธีใช้อย่างละเอียด [...]
karlos
Jul 3 '08 at 12:35 am
Hi , I’m trying to use this class with phpmaker , pls help me!
Thanks
Will
Jul 3 '08 at 2:09 pm
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.
Shain
Jul 5 '08 at 6:34 am
Thank you so much for putting this. This class is excellent and extremely easy to use.
Kazakbala
Jul 5 '08 at 11:43 am
The best class for working with images.
In future it could be return EXIF data from images )))
Bas
Jul 11 '08 at 6:55 am
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);
—
Simon66
Jul 22 '08 at 10:43 pm
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.
Senthil
Jul 23 '08 at 4:17 am
Hi Ian,
Its totally amazing…
Thanks for your help…
tronics
Jul 27 '08 at 10:09 am
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;
}
tronics
Jul 27 '08 at 10:23 am
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);
}
isnain
Jul 31 '08 at 10:03 pm
can this script make an image transparent?
Edwin Steenwinkel
Aug 5 '08 at 2:13 pm
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!
+ve
Aug 5 '08 at 9:37 pm
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();
?>
Deezaz
Aug 6 '08 at 5:39 am
where do i get the ‘thumbnail.inc.php’ file? that you hae required in the thnb nail code??
Banning
Aug 7 '08 at 10:13 pm
i dont understand in the img src variable for filename= while i was at work playing with this i put a complete url “http://filepath” now when i get home it doesn’t work. I don’t understand
Márcio Souza Duarte
Aug 8 '08 at 6:35 am
Congratulations Ian Selby, your Thumbnail class is very good! I’m using this class with CodeIgniter and worked very well.
Brasil->RS
Banning
Aug 8 '08 at 7:27 am
ok so as far as my problem goes i have this hosted on 3 diff sites.. 1) http://memovie.mobi/test.php 2) http://doughxpress.com/test.php 3) http://www.hixcorp.com/test.php
as you can see it only works on the second host… any thoughts on why that is? have you ever ran into this problem before? or has anyone on here ever ran into it?
Banning
Aug 8 '08 at 7:45 am
ok i figured out the problem… in your php.ini file you need to set session.save_path = /cgi-bin/tmp or at least that worked for me, now i can reference external images YAY!
Aug 12 '08 at 1:44 am
[...] class’ı ile ayrıntılı bilgiye http://www.gen-x-design.com/projects/php-thumbnailer-class/ adresinden [...]
whimZefx
Aug 16 '08 at 12:28 am
Great job mate!
What I really like about this script is that it works on the fly. You can chose to save the thumb image, or not at all. I’m using it on quite a number of my sites now and it is just so easy to use. It didn’t take me long at all to work out how to string together various classes and best of all, I’ve managed to use it to size images for use as backgrounds (in li and option tags) – without having to fuss with manually producing different sized images. Love the script.
Just one request for any future developments – currently the resize produces thumbs to a maxWidth and maxHeight value. I found that it would also be handy to have a minWidth and minHeight resize class as well … for those instances where you have a really long landscape image and you want to shrink it down and crop to a square. When there are hundreds of images, it’s hard to work out a ’standard’ maxWidth that would all arrive at a height that is equal to or greater than the cropSize. If there are minimum values set, then one can be sure that one will always get a square after a crop. Making sense?
d3vkit
Aug 17 '08 at 6:26 am
This is PERFECT! I’m using it for a webcomic I’m drawing, and look forward to having thumbnailed images for each comic in my archive. This is more than one could ask for, thank you very much!
Marcus Nyberg
Aug 17 '08 at 1:28 pm
Great class! Just what I was looking for. I am switching from ImageMagik to GD and will use this for my projects. My first change was to make the getcurrentheight and getcurrentwidth public.
Aug 18 '08 at 12:52 am
PHP Thumbnailer Class v2.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 f…
Hyra
Aug 20 '08 at 2:44 am
Awesome.
Currently have it running as a library within a CodeIgniter 1.6 install locally and works like a charm.
In my design i had used fixed aspect ratio of 150×95 for the thumbnails, which the class doesn’t seem to support, but for the picture stream of 100×100 thumbs with cropfromcenter it is just beautiful.
Aug 28 '08 at 6:59 am
[...] PHP Thumbnailer Class v2.0 – просто, но со вкусом [...]
Simon
Sep 10 '08 at 8:18 am
This is a great script, I have two requests though. Firstly to make the properties in the class protected instead of private to allow extensions to the class without touching your work directly.
Secondly the ability to make images a fixed height and width and to scale the image inside this box (giving a solid colour on the background). This has been asked for before.
I’ve tried to extend your class with this but I keep getting solid black lines down the right side of the image and I can’t figure out why, any tips?
Vic
Sep 10 '08 at 11:56 pm
Nice class. Good job
chris
Sep 11 '08 at 3:29 pm
When I set the max width and height above 127, getImageSize() always returns 127 for both width and height.
So if I did this:
$max_width = 500;
$max_height = 500;
$thumb = new Thumbnail($pathfilename);
$thumb->resize($max_width, $max_height);
$thumb->save($pathfilename);
list($new_width, $new_height) = getimagesize($pathfilename);
—-
And I’ll get:
$new_width = 127
$new_height = 127
The strange thing is that the actual resized image has the correct dimension (500 x whatever).
Again, this problem occurs only when I set the max width and height over 127. Below that, it’s fine.
Any idea how to fix this?
Thanks.
chris
Sep 11 '08 at 4:00 pm
ooops…. found the error…. it was on my MySql datatype. I set it to tinyint and the max number it can hold was 127.
Sep 12 '08 at 8:17 am
[...] I am explaining creating image thumbnail using PHP Thumbnailer Class v2.0 in 2 easy steps. I am assuming that, you are using Zend’s MVC with common directory structure [...]
chris
Sep 12 '08 at 7:54 pm
Hello… I have a few questions on your awesome script:
1) When I try to resize an animated GIF, the result shows only the first frame. How can I get it to keep the animation?
2) The result also changes the background color to black. Anyway to fix it? I tried to add Edwin’s code (#50 above) if( ($this->format == ‘PNG’) OR ($this->format == ‘GIF’) ), but it didn’t work.
3) If the original image is already smaller than the max width and height, can I have it skip the resizing process and save it as is?
Thank you very much.
chris
Dan
Sep 16 '08 at 1:04 pm
This is an excellent script! I’ve used it in a bunch of my sites. Thanks!!
Srdjan
Sep 22 '08 at 12:24 pm
I constantly get “The image “http://…/” cannot be displayed, because it contains errors.
I use both variable and static address, and have tried with several images… gd2 enabled.. dunno
$thumb = new Thumbnail($img_address);
Mike
Sep 23 '08 at 6:19 am
For everybody having the error:
�PNG++���+IHDR����������’����+PLTE����������^������IDAT8��A+�0ES!���%3B�9E\��`�%23.%3DE���*%3A+��r����o�����¢M����9���p�Ќ��G5�Ә�b����8+�G�^���%25��f���cD�4�9�ۮ�+6Ӽ��2′g��p��z9ݓ�\R���%3F�^�G�^|߶�^iޣ_���%2Bn��3�����IEND�B`�
I was having this same problem. Turns out it was a permission problem on the server. Setting the appropriate Read/Write permissions worked for me.
Adam
Sep 25 '08 at 5:56 am
Helo to Javier and tronics that watermark image or text dont work for Me.
I use php5 version and i dont now how use that your mods.
I add code like You say before last }
and in sample dont change antything so i got:
sample.php with:
show_image.php with:
$thumb = new Thumbnail($_GET['filename']);
$thumb->resize($_GET['width'],$_GET['height']);
$thumb->watermark(”watermark/watermark.png”);
$thumb->show();
exit;
And results is: show nothing (php5 version).
Please about some help i really need that watermark text or image.
Adam (sorry by broken english
)
Tarek
Sep 28 '08 at 2:45 am
Why can not I generate more than one thumbnail in the same page?!
I tried to __destruct() the first instance and it still dose not want to show the second thumbnail.
Please help.
Thanks,
Tarek.
lokesh
Oct 6 '08 at 5:48 am
i have got this error when try this script
Out of memory (allocated 35389440) (tried to allocate 14016 bytes) in /homepages/43/d254970719/htdocs/thumbnail.inc.php on line 152
pls give ans as soon as possible
Terry
Oct 10 '08 at 8:04 am
lokesh: try to add this to your script before you call the thumbnail function:
ini_set(’memory_limit’, ‘40M’);
Hope that it helps.
Yfer
Oct 12 '08 at 5:59 pm
Your script save me some time, thanks. But what the purpose of $this->oldImage $this->newImage $workingImage??? It’s doesn’t seem in use for something special… Or you wanted to handle some CTRL-Z functionality?
Adrian
Oct 17 '08 at 3:44 am
To fix problems with PNG and GIF transparency, we can use the code in comment #50 but it need one change.
Bad: $this->format == `PNG´
Good: $this->format == “PNG”
Use ” or ‘ , not ` or ´
Then, it works for me.
Sara
Oct 27 '08 at 8:30 am
Excuse me for my bad English, I wanted to ask is possible with this class size and add a watermark in an animated gif keeping the animation?
Lucas
Oct 28 '08 at 8:22 am
Somebody fixed the GIF´s black background problem? i tried using the Edwin Steenwinkel´s code but dont work. Thanks.
Michael Matney
Nov 4 '08 at 2:10 pm
I’ve modified the script for the watermark to simplify it. for my application only png files can be used for watermarks. So here is my code:
//Function to create watermark
public function watermark($imagesource){
$pathinfo = pathinfo($imagesource);
$watermark = @imagecreatefrompng($imagesource);
$startwidth = ($this->currentDimensions['width']);
$startheight = ($this->currentDimensions['height']);
imagecopy($this->workingImage, $watermark, $startwidth, $startheight, 0, 0, $startwidth, $startheight);
}
I must admit, I am having a difficult time debugging since I don’t under the $this–>workingimage and php.net doesn’t seem to explain –> or what $this refers to, so that may be my problem.
Bottom line, No watermark is created, but no errors are generated either.
the line calling this functions is:
$thumb->watermark(”/usr/local/apache2/htdocs/images/watermark.png”);
Michael Matney
Nov 4 '08 at 11:05 pm
I corrected the above code example that was provided by Javier. I found two problems in the code. The first is the reference of “workingimage” – the letter i in image should be capitalized “workingImage” not sure if this would have created a problem. I dont think so. However the real problem was with the quotations used around the “png”, “jpeg”, “jpg” – the ascii character used for quote is invalid in php, and I corrected it with the correct quotation marks. This solved the problem and now the function works. Heres the correct code:
//Function to create watermark
public function watermark($imagesource){
$pathinfo = pathinfo($imagesource);
$var1 = $pathinfo['extension'];
$var2 = “png”;
$var3 = “jpeg”;
$var4 = “jpg”;
$var5 = “gif”;
if($var1 == $var2){
$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);
}
Of course the watermark appears at the bottom of the image, and for my purposes, and Im assuming other peoples purposes, the watermark should be centered to the image. I will repost the code once I have worked this out
Paul
Nov 6 '08 at 8:23 am
This is a fantastic resource – what would be really useful to see in a next version is:
resize image – specify max OR minimum width/height
crop image – specify width and height when cropping from centre.
Great work, look forward to next release
anik
Nov 6 '08 at 11:09 am
can any one tell me how can i show multiple thumbnail image in one page ..please i need it urgent !!
Jason
Nov 17 '08 at 5:08 pm
I can not get gif’s to display for the life of me. Everything else works fine. I even hard coded show_image.php for a couple different gif files and i get the following as alt text of the produced img tag:
“The image “http://intranet.domain.com/show_image.php” cannot be displayed, because it contains errors.”
Any ideas?
Great script by the way!
Jason
Nov 18 '08 at 5:25 pm
Figured out the GIF issue. open_base_dir was preventing ImageGif from working properly. Not sure why this only affects gif and not jpg or png.
Regis
Nov 20 '08 at 8:47 pm
Great class man! saved me a lot of work. I gave you 5 bucks, not a lot, but hopefully more will follow…
Thanks!
AFisher
Dec 3 '08 at 6:25 pm
Amazing class… works like a charm for all sorts of resize and watermarking tasks.
Is there an easy way to tint an image to greyscale and/or sepia tone?
Thanks
Dan
Dec 5 '08 at 12:48 am
Great script. It dies though when I start using large images. I’m not sure where:
ini_set(’memory_limit’, ‘40M’);
might fit in to help with this problem.
Thanks!
Tom
Dec 8 '08 at 10:11 am
Hi,
This is a brilliant class, thanks for sharing it.
I’m not sure how to go about scaling an image down and then cropping it so it is exactly 550 * 400. The problem I’m having is that when I resize the image to be a maximum of 550 px wide and maximum 400 px high, it outputs at 550 x 473 because of the original image ratio, thus making it already too small to crop to size.
Is there any way around this?
Thanks
Rob
Dec 10 '08 at 6:58 pm
If you don’t want your images “upscaled” from the thumbnailer (as in, a small image being scaled up to the max height/max width) replace the function in thumbnail.inc.php named public function resize() with:
/**
* Resizes image to maxWidth x maxHeight
*
* @param int $maxWidth
* @param int $maxHeight
*/
public function resize($maxWidth = 0, $maxHeight = 0) {
$this->maxWidth = $maxWidth;
$this->maxHeight = $maxHeight;
if($this -> currentDimensions['width'] > $maxWidth || $this -> currentDimensions['height'] > $maxHeight) {
$this->calcImageSize($this->currentDimensions['width'],$this->currentDimensions['height']);
if(function_exists(”ImageCreateTrueColor”)) {
$this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
else {
$this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
ImageCopyResampled(
$this->workingImage,
$this->oldImage,
0, 0, 0, 0,
$this->newDimensions['newWidth'],
$this->newDimensions['newHeight'],
$this->currentDimensions['width'],
$this->currentDimensions['height']
);
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $this->newDimensions['newWidth'];
$this->currentDimensions['height'] = $this->newDimensions['newHeight'];
}
}
hope this helps
— this may even be a bug unless you developed it to automatically blow-up the size of the thumbnail. . but then again, isn’t a “thumbnail” supposed to represent a big picture into a scaled down one and not the opposite?
Just my 2cents
I may edit this file and repost it to be more optimized. If that’s okay
Rob
Dec 10 '08 at 7:01 pm
@Anic: if you want to display more than one thumbnail, you’ll have to just make new objects of the thumbnail class. such as:
include “thumbnail.inc.php”;
$myimages = array(”1.jpg”, “2.gif”, “3.png”, “4.jpg”);
foreach($myimages as $image) {
$thumb = new Thumbnail($image);
$thumb->resize(75, 75);
$thumb->show();
unset($thumb);
}
Hope this helps along with others as well.
beginer
Dec 15 '08 at 7:22 am
Hello San Francisco from Moldova!
A BIG thanks for your class!
Johan de Jong
Dec 15 '08 at 8:56 am
I created a ‘Real Crop’ function which is very useful. Just past this code at the bottom of the class (PHP4)
currentDimensions['width'] > $this->currentDimensions['height']) {
$this->resize(0, $size);
} elseif($this->currentDimensions['width'] currentDimensions['height']) {
$this->resize($size, 0);
}
$this->cropFromCenter($size);
}
?>
virtue
Dec 17 '08 at 10:38 am
Awesome script. Very useful, easy to customize, got watermarking to work. Made my life a lot easier. Thanks man!
AFRC
Dec 19 '08 at 2:34 am
Hi,
I use your class long time ago, and the last days i got this error:
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in path_hidden/thumbnail.inc.php on line 21
Im using php5, and i never changed the class.
Do you know why this happened ?
Thanks for your help.
mchris
Dec 22 '08 at 2:48 am
Hey man, good work, thanks alot! =)
warren
Dec 22 '08 at 9:27 pm
As a suggestion, this class will be great if it supports auto contrast / level
Darmen
Dec 28 '08 at 10:17 am
Hi Ian.
You did real good job – thank you very much.
But I got some issue on using it.
I resize my JPG image (500px x 300px) to 420px by width and I noticed, that the actual file size of resized image is greater, than the original’s… What’s wrong?
P.S. Happy New Year!
Eoghan O'Brien
Dec 29 '08 at 5:30 am
Hi, I’ve been using your class, its come in really handy, its easy to use and I’m pretty impressed, however I feel the script really needs some image compression as most of the images I crop/resize end up being quite large.
If there is an easy way to implement this please e-mail me as this is very important to a project I’m currently working on.
Cheers
hailey
Dec 29 '08 at 6:36 pm
Missing code in my previous post:
If outside codeigniter, i can use this to generate the thumbails:
“<i />”
but i don’t know how to use it in codeigniter.
hailey
Dec 29 '08 at 6:31 pm
Hi guys, i’ve added the thumbnailer class inside codeigniter’s library. I can generate a thumbnail by calling this function:
function createThumb()
{
$this->thumbnail->thumbnailer(”assets/images/test.jpg”);
$this->thumbnail->resize(200,200);
$this->thumbnail->show();
$thumb->thumbnail->destruct();
}
But this willl generate a page with only the image. But i want to use the function dynamically. In other words, i’m calling the image path from the database, and the thumbnail will be generated accordingly.
If outside codeigniter, i can use the ” but i don’t know how to use it in codeigniter.
PLz englighten me. I’m still new to codeigniter.
bdogget
Jan 4 '09 at 3:41 pm
This is working great for me except when my images start getting into the 3 to 4 meg size. Just seems to quit.
Ian
Jan 4 '09 at 5:33 pm
Probably PHP running out of memory… images that large will use a lot of CPU / memory to process, especially depending on the quality / dpi. Check your php.ini and see what the memory limit is, then try upping it more… should help
after7days
Jan 11 '09 at 7:45 am
Hi there.
Great work, really, amazing!
I’ve got only one question – is it possible to work with distant files?
Because if filename is http://something.com/image.jpg, the script shows “Error: file not found” image…
Rachid
Jan 20 '09 at 6:33 am
i have JPG image with width:3072 and height:2304 and cant resize it, is there a limit of size
Ian
Jan 20 '09 at 11:31 am
No, but you’re probably running into PHP’s memory limit. Try raising it in your php.ini file (probably will need a lot to deal with images of that size)
Scott
Jan 22 '09 at 6:11 pm
Hi Ian,
Can you tell me the solution when cropping an image and getting this 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`‚
Fatal error: Cannot break/continue 1 level in /home/designfi/public_html/includes/templates/thumbnail.inc.php on line 173
jt
Jan 28 '09 at 8:51 pm
Hey Ian,
Is there a way to make the resized image sharper or higher quality than the 100% setting?
For our resized images to 120×100, 100% they come out quite blurry compared to photoshop resized images outputted at 60%.
staaky
Feb 1 '09 at 4:43 pm
Nice work on the script.There’s a bug in resize. In order to make the image come out right if it’s smaller then both maxWidth and maxHeight this change is required. Without this either maxWidth or maxHeight become a minimum for that dimension instead of a maximum.
if ($this->maxWidth > 0)
if ($this->maxWidth > 0 && $width > $this->maxWidth)
Same goes for the height.
iHandler
Feb 3 '09 at 1:18 am
Good Scripts ! I tested it around and it works alright. Nice ~
Is it possible to use the CLASS directly instead of passing parameters into a PHP page.
Option 1: Use the Class directly with IMG TAG (this does NOT work)
————————————————————————–
include_once(’thumbnail.inc.php’);
$thumb = new Thumbnail(’sample.jpg’);
$thumb->resize(60,60);
print ’show() . ‘ >’;
unset($thumb);
Option 2: Pass Parameters to PHP Page (This works)
————————————————————————–
The reason I want to do this is to HIDE the “show_image.php” pages to the public. And I also like to use the Class directly inside my PHP page.
Please help !
Ian
Feb 3 '09 at 8:32 am
You can always use the save function then show them inline. The reason you can’t use show directly is because it needs to send headers with the image data… and if you’ve already output headers on your page, you’ll get nasty errors
iHandler
Feb 3 '09 at 7:08 pm
Thanks Ian, I see the reason now and you are right, I tested it around and I got a nasty errors if I “force” it to do so.
I also have a new idea to do it via using the class Directly.
Step 1: Use the CLASS (you created) directly and Save the files to a “Images” folder
Step 2: Use the IMG TAG to have a reference linkage to this folder such as
I believe it works. However, if I keep doing this, my webserver loading will be a lot since everytime it runs “save function”, I am thinking if it is possible to have a “cache” folder or any other detection to avoid “genereate” the same images, if so, do you know how?
My webpage contains 15 to 20 thumbnail images in a page. I wish to have a COOL way to accomplish this task…~
Again, thanks for your quick reply. ^___^”…
Ian
Feb 3 '09 at 7:53 pm
The class itself doesn’t have any caching built in (next version might, however), but it shouldn’t be too hard for you to write your own. Just check for the existence of a file on your system (by some naming convention), and use it if it exists, otherwise generate the thumb.
You could also write a script to “prime” that cache as well, to help offload some of the processing when a user views the page.
aaron
Feb 4 '09 at 1:23 am
SUPER CLASS …solved a hell lot of problems for me ..Great work guys
lryo
Feb 5 '09 at 1:14 pm
Hello,
I import your class in my project but I have an error…
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in *****/htdocs/ressources/VresourAdm/thumbnail.inc.php on line 4
But I don’t modify your class…
Do you have an idea ???
Thanks
Ian
Feb 5 '09 at 1:21 pm
Looks like you’re using the wrong version of the class… the PHP 5 one won’t run on PHP 4
lryo
Feb 5 '09 at 1:24 pm
I have download a PHP5 version… and my php version is 4.4.9.. sorry …
Thanks !!
lryo
Feb 5 '09 at 1:34 pm
I have a new question… The file name may be : http://www.monsite.com/test.png ???
Thanks
lryo
Feb 7 '09 at 1:38 am
I use the class like this:
$thumb = new Thumbnail(’http://www.monsite.com/test.png’);
$thumb->resize(300,300);
$thumb->cropFromCenter(120);
$thumb->save(’test/test.png’.$ext,100);
But as I get this message:
Error : File not found.
Why ??
Thanks
Nate
Feb 7 '09 at 9:55 am
Does anyone else notice that when you upload an image smaller than the resize dimensions you set, it stretches the image to the full size. If you upload a smaller image, it gets really pixelated and looks like crap.
If the image is smaller than the resize dimensions, shouldn’t it just leave it alone? Since the dimensions you pass in are to keep the uploaded image within those dimensions, not to resize the image to them.
Nate
Feb 7 '09 at 10:10 am
I just read @staaky comment above and that fixed the problem. Good job!
Ryan
Feb 9 '09 at 3:25 am
I just can’t get this to work, I just get a missing image placeholder.
When I look at the activity log for ’show_image.php’ it says “Internal Server Error”
Any ideas? I’ve not modified anythinh, ttried both Php4 and 5 versions (My server is running PHP 5)
tricky dicky
Feb 11 '09 at 10:02 am
I’ve been banging my head against the screen for the last umpteen hours and I think I may have found a bug! Definately a problem!!
Is there any specific reason why $thumb->rotateImage(’CW’) produces an error UNLESS it’s preceeded by another function?
$thumb = new Thumbnail($_GET['filename']);
$thumb->rotateImage(’CCW’);
$thumb->show();
$thumb->destruct();
produces the following error:
[Wed Feb 11 17:54:53 2009] [error] [client 127.0.0.1] PHP Warning: imagerotate() expects parameter 1 to be resource, null given in C:\\tricky_dicky\\thumbnail.inc.php on line 667, referer: http://tricky_dicky/
[Wed Feb 11 17:54:53 2009] [error] [client 127.0.0.1] PHP Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\\tricky_dicky\\thumbnail.inc.php on line 486, referer: http://tricky_dicky/
Whereas
$thumb = new Thumbnail($_GET['filename']);
$thumb->resize(250,250);
$thumb->rotateImage(’CCW’);
$thumb->show();
$thumb->destruct();
performs fine!
I’m running Apache/2.0.59 (Win32) PHP/5.2.5 (although my host uses PHPv4 – hense I’m using php4_thumbnail_v2 class).
Would love to hear comments about this.
Thanks.
diego
Feb 11 '09 at 10:54 am
If the file extension is JPG (f.example) the script crashes ;(
DrQ
Feb 15 '09 at 3:56 pm
Hi Ian!
i really love this class! but you should check out this little codetweak:
I often use your class but got several errors because my userfileuploads. Sometimes the extensions .gif were in fact jpgs and vice versa.
In your class you decide what to do by looking at the file ext. That probably works most of the time, but I got some nasty errors because of it .
So i modified at line 130-> your code
to this:
$type = getimagesize(strtolower($this->fileName));
if(stristr($type['mime'],’jpeg’)) $this->format = ‘JPG’;
elseif(stristr($type['mime'],’gif’)) $this->format = ‘GIF’;
elseif(stristr($type['mime'],’png’)) $this->format = ‘PNG’;
this provides that you can really be sure, that the right method is used for the right imagetype.
Hope this helps
DrQ
Sunchaser
Feb 18 '09 at 8:28 am
I needed to made indipendent image type recognization from the extension:
if ( $this->error == false )
{
list($orig_x, $orig_y, $orig_img_type, $img_sizes) = GetImageSize($this->fileName);
if ( $orig_img_type == 1 )
$this->format = ‘GIF’;
elseif ( $orig_img_type == 2 )
$this->format = ‘JPG’;
elseif ( $orig_img_type == 3 )
$this->format = ‘PNG’;
else
{
$this->errmsg = ‘Unknown file format’;
$this->error = true;
}
}
webprogrammer
Feb 24 '09 at 8:51 am
You validate you filetype via file’s extensions. It’s wrong.
Don’t use this code:
if(stristr(strtolower($this->fileName),’.gif’)) $this->format = ‘GIF’;
//check if jpg
elseif(stristr(strtolower($this->fileName),’.jpg’) || stristr(strtolower($this->fileName),’.jpeg’)) $this->format = ‘JPG’;
//check if png
elseif(stristr(strtolower($this->fileName),’.png’)) $this->format = ‘PNG’;
//unknown file format
else {
$this->errmsg = ‘Unknown file format’;
$this->error = true;
}
Use next :
$imgSizeType = getimagesize($this->fileName);
if(isset($imgSizeType[2]) && $imgSizeType[2] == 1){
$this->format = ‘GIF’;
} elseif(isset($imgSizeType[2]) && $imgSizeType[2] == 2){
$this->format = ‘JPG’;
} elseif(isset($imgSizeType[2]) && $imgSizeType[2] == 3){
$this->format = ‘PNG’;
} else {
$this->errmsg = ‘Unknown file format’;
$this->error = true;
}
When you send your file via form, your source file has extension like “.tmp” , that’s why you must change that place in the code.
Ian
Feb 24 '09 at 9:08 am
You’re right that I shouldn’t be checking by extension (a bug that I’ve been meaning to fix for a while), however, you’re wrong about the .tmp part. Even if you use this in conjunction with an uploaded file, you would never want to use the class to manipulate your images until you’ve actually saved the uploaded file on the filesystem somewhere. That way you can do other things with it if needed (make sure the filename’s unique, possibly even virus scan it, etc.)
Thanks for the tip tho, I’m definitely going to remove that code in the upcoming version of the class.
Alexei
Mar 2 '09 at 6:36 am
resize function..
if($this->currentDimensions['width'] > $maxWidth && $this->currentDimensions['height'] > $maxHeight) {
$this->maxWidth = $maxWidth;
$this->maxHeight = $maxHeight;
}else{
$this->maxWidth = $this->currentDimensions['width'];
$this->maxHeight = $this->currentDimensions['height'];
}
or
if($this->currentDimensions['width'] > $maxWidth && $this->currentDimensions['height'] > $maxHeight) {
$this->calcImageSize($this->currentDimensions['width'],$this->currentDimensions['height']);
}else{
$this->newDimensions['newWidth'] = $this->currentDimensions['width'];
$this->newDimensions['newHeight'] = $this->currentDimensions['height'];
}
Hilken
Mar 3 '09 at 8:52 am
1) When I try to resize an animated GIF, the result shows only the first frame. How can I get it to keep the animation?
Any work-around to solve this? Thanks!
W
Mar 13 '09 at 9:32 pm
Can you also implement round corners in the image class? It will make this class much useful
lightflowmark
Mar 17 '09 at 6:36 am
Thanks for this class, very useful!
Quick function for setting the format of the output image – useful if you want to use e.g. a naming convention to keep track of images:
/**
* sets format of output image by setting $this->format
*
* @param string $format
*/
public function setFormat($format)
{
$format=strtoupper($format);
$allowedFormats=array(’JPG’,'GIF’,'PNG’);
if(array_search($format,$allowedFormats))
{
$this->format=$format;
}
else
{
$this->errmsg = ‘Unknown file format’;
$this->error = true;
}
}
Aimi
Mar 19 '09 at 1:22 am
Finally, after trying many solutions to get rid of black background in GIFs in vain.
This is it :
in function RESIZE
before IMAGECOPYRESAMPLED function
if( $this->format == ‘PNG’ || $this->format == ‘GIF’) {
imagealphablending($this->workingImage, false);
$colorTransparent = imagecolorallocatealpha($this->workingImage, 255, 255, 255, 0);
imagefill($this->workingImage, 0, 0, $colorTransparent);
imagesavealpha($this->workingImage, true);
}
if ( $this->format == ‘GIF’){
imagetruecolortopalette($this->workingImage, true, 256);
}
Koen
Mar 23 '09 at 4:50 am
When resizing it would be nice if you could specify a fixed width and height instead of a max. The the image should be resized and cropped to meet the fixed dimensions. Now thumbnails will have a different sizes…
Gesen
Mar 23 '09 at 4:56 am
Hi!
I’m getting the “File not found” error message when trying to upload som files. Why do I get this error message? I mean, the files are clearly on my computer. Does it have anything to do with the image file size?
I would really appreciate if anyone could help me out on this one!
Jason
Mar 23 '09 at 5:11 am
Love it, easy and well written. This library will be used as the default thumbnailer class for the next phpdevshell project release.
Ian
Mar 23 '09 at 10:29 am
Awesome, I’ll try and make sure to let you know when the next version comes out as well!
Matti Niemelä
Mar 24 '09 at 4:16 am
Source looks good with a quick glance.
You should most definitely make next version use imagemagick if available.
I’ve done some testing with GD and IM, and IM just produces a lot higher quality images in less filesize. GD sometimes makes a big mess with some type of JPEGs.
Please, add IM support!
Banning Stuckey
Mar 25 '09 at 12:04 pm
do im back to wonder why this doesnt work session.save_path BUT doughxpress.com works… i have filename=http://filepath… it seems that sometimes i can link to an image with a absolute file path and other times i cant.. any suggestions or help on why?
Jan
Mar 25 '09 at 12:26 pm
I am getting the same error as Gesen.. It won’t process large images (3MB) so I reduced the size to 600K, it works on my local machine but not when I upload it on a hosted server. Is there any limit on file size or anything that might obstruct processing large images. Otherwise it is really great idea, thanks for that.
Ian
Mar 26 '09 at 8:50 am
Matti, I fully intend to do that! I’m slowly, but surely, getting some work done on the next version of the class, so keep your eyes peeled
Alex
Apr 4 '09 at 1:12 pm
How would you amend this script to make it work on images echoed from a databse..
Any Idea?
Apr 10 '09 at 8:18 am
When trying to resize the following ERROR appears:
Warning: Cannot modify header information – headers already sent by (output started at /var/www/web165/html/v2.0/inc/header.inc.php:4) in /var/www/web165/html/v2.0/inc/thumbnail.inc.php on line 288
�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��B`�
Fatal error: Cannot break/continue 1 level in /var/www/web165/html/v2.0/inc/thumbnail.inc.php on line 167
maleo
Apr 13 '09 at 8:06 am
is this script command base on imagecopyresampled ? i used this command before for my site and cause me alot of cpu usage problem when there’s spike traffic. i also use imagedestroy after i run the script but that don’t solved my cpu problem.
my vps have 512 mem and 150Mhz (quad core Q6600 – equal to single core 600mhz Q6600) and every i got spike my website run very slow but never out of memory.
my site is a gallery site with +/-200.000 files and create 50 thumbnail for every display page. and i got approx 30k pageview every day.
is your script have more efficient technique so it can reduce cpu usage?
Thank you Ian.
maleo
Apr 13 '09 at 8:10 am
Sorry i double post since i have one more question and maybe you can help me with this.
Do you know what image is more easy and light to resize? is jpg lighter to resize than gif? of maybe gif is lighter?
thank you.
Tyler
Apr 15 '09 at 1:03 am
I think this is the best script out there. I had to use the “ini_set(’memory_limit’,'45M’);” to be able to handle resizing photos of about 2.5MB in size. But over all I love the script!
devKev
Apr 23 '09 at 10:15 am
You have a spelling error in the API section under the resize function. It says “Resizes the image to be now wider than maxWidth”. I think its suppose to be “no wider than maxWidth”. Thanks for the class.
mgsmus
Apr 26 '09 at 6:19 am
great script,
is there a way to add border to image without reflection?
i tried $thumb->createReflection(0,0,0,true,”#FFFFFF”); but it doesn’t work
Anil Konsal
May 11 '09 at 4:16 am
VERY NICE CLASS Dear. Well Done!!!
Mariano
May 17 '09 at 1:15 pm
You’ve done a great job with this class. Thank you Ian
Al
May 21 '09 at 4:32 am
Hi, thanks for the code, below are three functions to create a centred, square thumbnail. Hope they are of interest.
//////////
public function getAspect(){
if ($this->currentDimensions['width'] > $this->currentDimensions['height']){
$this->aspect = “LS”;
} else if ($this->currentDimensions['height'] > $this->currentDimensions['width']){
$this->aspect = “PT”;
} else {
$this->aspect = “SQ”;
}
return $this->aspect;
}
//////////
///works out the percentage reduction to make sure image fits square
public function getMinSize($size){
//
$ta = $this->getAspect();
///
if ($ta == “LS”){
$p = ($size/$this->currentDimensions['height'])*100;
} else if ($ta == “PT” || $ta == “SQ”){
$p = ($size/$this->currentDimensions['width'])*100;
}
//
return $p;
}
//////////
///wrapper for aspect and minsize
public function squareThumb($size){
$this->resizePercent($this->getMinSize($size));
$this->cropFromCenter($size);
}
Andrei
May 25 '09 at 1:30 pm
Just wanted to say a big Thank You.
Any news on the next version of this class?
Ian
May 25 '09 at 8:23 pm
Thanks! Hope to have the next version of the class ready very soon. I’m currently working on testing and docs… so keep checking back!
Đào Anh Phúc
May 26 '09 at 9:10 pm
that’s good. thanks
InvisGhost
May 31 '09 at 9:23 pm
Awesome, Ive been using this for a while now, Interested to see what is in the next version.
As a suggestion, Think you can add url support for thumbnailing remote images? That would be great! Thanks again!
Fernando
Jun 1 '09 at 12:38 am
Thank you for your class – I using it on my few projects.
Waiting for a new version.
webprogammer
Jun 2 '09 at 8:18 am
Hi Al, The use of the getAspect(), getMinSize($size), squareThumb($size) function like?
EX:
webprogammer
Jun 2 '09 at 8:19 am
Hi Al, gHow to use getAspect(), getMinSize($size), squareThumb($size) function?
tom
Jun 3 '09 at 11:16 pm
any solution for the animated gif problem? is it posible to keep the animation after resizing?
lightflowmark
Jun 4 '09 at 5:59 am
Hi – please change private properties / methods to protected, subclassing is a real pain otherwise!
Also, is there any mileage in improving the error handling? Displaying an image is not always the correct thing to do, for instance when running this in a script or as a small part of a larger application.
I would think that throwing an exception with a custom exception class would be more appropriate. You could then choose the Exception handler based on a (protected!) property, and have an exception class to display an error image, and another to do something more traditional, as required. I’m happy to write this code & provide some tests if you’re interested in it, let me know.
Cheers,
Mark
Ian
Jun 4 '09 at 8:49 am
Mark,
The next versrion of the library (soon to be released when I finish up the docs) addresses all those issues. Everything throws exceptions now, and error handling is more robust.
Pedram
Jun 8 '09 at 5:14 am
Thanks for sharing your hard work ! it works well ! but i don`t know why when i upload large files ( more than 500 K i think nothing happens and since i use it in backed of my ajax i don`t know what the error can be, please tell me how to solve it cuz i`m using it and i can`t show thumbnail of large images in search result, thanks in advance
Zach
Jun 10 '09 at 5:38 am
Is their a size limit for the images being used, because it seems that if I use an image over 1200 px by 1200 px or so, the script just dies. Any thoughts?