Generating thumbnails with PHP and GD
This rather old article is now moved to icant.co.uk where it belongs and I ditched the gd1 information. It describes how you can generate thumbnails from images on the fly using PHP and the gd library.
You can check it at: http://www.icant.co.uk/articles/phpthumbnails/


April 7th, 2005 at 3:59 am
Happened upon your old script for batch processing thumbnails. I have tried the script, but get an error that suggests I am specifying the directory incorrectly. Example below:
Warning: imagecreatefromjpeg(9902370_6.jpg): failed to open stream: No such file or directory in /home/onethous/onethousandlakes-www/thumbnail_generator.php on line 41
The directory and file are present. The directory is one level below the script (e.g. ‘images’) and the folder for thumbnails is below that (e.g. ‘images/thumnails’). I’ve tried varying the designation of the location of the directory, but none of those work. Does the script need to be in the same directory or is there another problem. Thanks for a reply.
April 26th, 2005 at 8:20 am
I’m having the same problem.
April 27th, 2005 at 10:34 am
The error you mentioned means that the image file it tries to load is not there. If you’d email me a URL I could try to trace the error.
May 11th, 2005 at 12:26 pm
Works great on Linux Debian Woody.
Just have to install php4-gd package with apt-get :)
May 30th, 2005 at 12:15 pm
Undefined variable: tmparr in C:Inetpubwwwroottoolsthumbnail_generatorthumbnail_generator.php on line 24
I get Undefined Variable tmparr, How to fix this???
Answer
Check the error reporting section in your php.ini and disable the warnings. Those should never be displayed on a live environment anyway, as they tell too much about your setup.
I guess you use IIS, I never did that, so I cannot help you further.
June 6th, 2005 at 8:55 pm
Just wanted to say I found your images script INCREDIBLY simple to understand and even more simple to implement. I modified a bit but added an if statement to the function I thought I might share.
if (($old_x <= $new_w) and ($old_y <= $new_h))
{
$thumb_w=$old_x;
$thumb_h=$old_y;
}
Basically I found that this script stretches images that are small and that is not always a good thing so I added that little bit of code and it worked like a charm:) Thanks again for sharing the code!
June 13th, 2005 at 6:26 pm
This is the only image resize script that outputs images that I’ve found easy to implement and that works. I have one problem though. I’m trying to convert a 640×480 image to 300×225, but for some reason its getting output at 300×168 ??? I have no idea why this is happening. Here’s my code:
if ($result) {
// Move the file over.
if (move_uploaded_file($_FILES['stackimg_lg']['tmp_name'], “uploads/$filename”) && $s) {
$i = $_FILES['stackimg_lg']['name'];
$filemoved = TRUE;
$updir = “uploads/”;
echo ‘Large Stack Image for ‘ . $f . ‘: ‘ . $filename . ‘ has been uploaded!
Copying and resizing for Small Stack Image…
‘;
// create copy of uploaded file
if ($filemoved) {
$filecopied = copy($updir . $filename, $updir . $filename . ‘.bak’);
} else {
$ferror = ‘copied to create the small Stack Image.’;
}
// verify file copy then rename
if ($filecopied) {
$stackimg_sm = $f . ‘stack_sm’ . ‘.’ . $extension1;
$stackimg_lnk = ‘admin/’ . $updir . $stackimg_sm;
$created_smstack = rename ($updir . $filename . ‘.bak’, $updir . $stackimg_sm);
} else {
$ferror = ‘moved to resize the small Stack Image.’;
}
// verify rename then resize
if ($created_smstack) {
createthumb($updir . $stackimg_sm,$updir . $stackimg_sm,300,225);
echo ‘Small Stack Image for ‘ . $f . ‘ has been successfully created. Filename: ‘ . $stackimg_sm . ‘
‘;
June 13th, 2005 at 7:05 pm
In addition to my last comment, I tried to set the output ratio to 400×300 and it came out 400 × 225, so if I set it to 300,300 I get what I need 300 × 225. Any ideas?
createthumb($updir . $stackimg_sm,$updir . $stackimg_sm,300,300);
June 28th, 2005 at 2:51 pm
You should also note that using $system1 to get the extension is NOT good!If there are more dots in the filename, this is array screwed!Instead use
$ext = sizeof($system);
$system[$ext];
so you will always get the last element of the array!
Thanx!
June 28th, 2005 at 4:50 pm
hu hu,
$system[$ext - 1];because array begins with 0 ;)but this one should do the same trick:
end($system)(note : another solution with pathinfo() …)
thkx for this nice and elegant script
July 5th, 2005 at 6:34 pm
Very helpful script, saved me a lot of time, also thanks to the guies at phpbuilder who knew to send me here.
July 21st, 2005 at 8:04 pm
Ooops, Pheuh is right!
I replied quickly and didn’t check what i typed!
August 25th, 2005 at 11:26 am
What about Generating Images From HTML
In Other words i mean to say How Can you Generate Images of an html file on your server
October 2nd, 2005 at 4:21 pm
The earlier commenters are correct that the script only works if in same directory as images – not advisable, it is better to include it from non-public folder…to make the script work it is a simple addition of the following ( I think the author just forgot to add this last bit in the tutorial)…just add the dir_path in the existing code like so:
foreach ($pics as $p)
{
createthumb($imagefolder . $p,$thumbsfolder . “tn_”.$p,90,90);
}
Bear in mind I think you need to include the trailing slash for your directory too, eg, $imagefolder = ‘/path/to/my/dir/’
NOT without last slash!!!
But a great little script, many thanks to the author.
Zuko
October 2nd, 2005 at 5:37 pm
I have a problem myself. I’m currently getting this:
Warning: imagejpeg(): Unable to open ‘images/cam_s.jpg’ for writing in /home/chris/public_html/chris/right.txt on line 39
Any ideas? Contact me at inkyt5@gmail.com if you have an answer please :)
October 8th, 2005 at 8:18 pm
This script covered exactly what I was looking for, except that it seems to be generating thumbnails for all images in the directory on every execution.
Is there a way to have the script check the directory and the thumbs directory and only create thumbs for images that do not yet have a thumbnail?
I’ve been playing with the ditchtn function, but my php skills are not yet good enough to write this.
Thanks for everything, Greg
October 20th, 2005 at 7:16 am
I believe I have the script working right, but for some reason, I’m getting black images instead of the image that was to be resized.
Any idea why this is happening? Thanks for an great script. Hope I can get it working.
Thanks,
Fish ><>
October 21st, 2005 at 1:38 am
Its weird, but I resaved the images I was uploading in PS and it started working. Is it possible that the file was saved as Progressive and it didnt like that? Just wondering.
October 21st, 2005 at 2:02 am
I was having the same stretching problem someone else mentioned. I changed a couple of lines and its working properly now:
if ($old_x > $old_y)
{
$thumb_w=$new_w;
//$thumb_h=$old_y*($new_h/$old_x); OLD LINE
$thumb_h=($new_w/$old_x)*$old_y;
}
if ($old_x < $old_y)
{
//$thumb_w=$old_x*($new_w/$old_y); OLD LINE
$thumb_w=($new_h/$old_y)*$old_x;
$thumb_h=$new_h;
}
if ($old_x == $old_y)
{
$thumb_w=$new_w;
$thumb_h=$new_h;
}
October 28th, 2005 at 4:18 am
I have the script working fine with images that are under 1Mb. However, when trying to create a thumbnail for a 1.95Mb image I encounter the following error message…
“Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 13824 bytes)
in /vhosts/twintownsdental.com.au/www/labcards/labcards.php on line 94″
How do I stop this from happening? What is causing this?
Cheers,
Chris
November 10th, 2005 at 7:24 am
I thought I was learning PHP pretty good, but I guess not. I’ve tried all I can think of, but still get nothing but a screen full of error messages citing that on lines 41, 42, 59, and 67, the functions,
imagesx()
imagesy()
imagecopyresampled() and
imagedestroy()
are not valid image resources.
The machine has current GD running, I’ve modified chmod, absolute path versus relative path, etc. but no luck.
I’m sure this is a simple one, but would greatly appreciate learning what I’m doing wrong.
Thanks
November 14th, 2005 at 9:56 pm
Hi,
Yes, and I wonder though how to display thumbnails on the browser like 5 pictures every roll and maybe 10 roll per pages and link to the next page showing more itmes and so on?
Any ideal at all?
Thx..
December 11th, 2005 at 5:42 pm
hi- this script is very good and is exactly what I wanted for my photography database. The only thing I found was that I get errors if the photo I upload has a .JPG or jpeg or JPEG extension, but i t works fine with the .jpg extension. I’m guessing it’s the way the PHP build with GD libraries, but I am unsure of how to check if this is indeed the case.
December 14th, 2005 at 10:10 pm
HI
Can any body help me, I have configured gd library then why this code is creating some binary codes on my browser window
< ? header(“Content-type: image/jpeg”); ?>
$filename = “12.jpg”;
$thumbSize = 100;
list($width, $height) = getimagesize($filename);
if($width > $height){
$new_width = $height;
}else{
$new_width = $width;
}
$sX = ($width-$new_width)/2;
$sY = ($height-$new_width)/2;
$image_p = imagecreatetruecolor($thumbSize, $thumbSize);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, $sX, $sY, $thumbSize, $thumbSize, $new_width, $new_width);
imagegif($image_p, null, 100);
?>
</>
$filename = “11.jpg”;
$thumbSize = 100;
list($width, $height) = getimagesize($filename);
if($width > $height){
$new_width = $height;
}else{
$new_width = $width;
}
$sX = ($width-$new_width)/2;
$sY = ($height-$new_width)/2;
$image_p = imagecreatetruecolor($thumbSize, $thumbSize);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, $sX, $sY, $thumbSize, $thumbSize, $new_width, $new_width);
imagegif($image_p, null, 100);
?>
</>
e>
January 2nd, 2006 at 9:30 pm
I’m having the same problem as chuck, imagesy and imagesx don’t seem to be reading valid resources… help anyone?
January 12th, 2006 at 10:29 pm
I am having the same problem as chuck and chris where I am getting several errors on lines that contain $src_img so it looks like $src_img=imagecreatefromjpeg($name) and $src_img=imagecreatefrompng($name) are not giving a valid resource. The errors look like
Warning: imagesx(): supplied argument is not a valid Image resource in……..
Warning: imagesy(): supplied argument is not a valid Image resource in……..
Warning: imagecopyresampled(): supplied argument is not a valid Image resource in……
And there are several other lines
January 13th, 2006 at 9:53 pm
Hi,
I have fixed my problem listed right above the problem it was to do with the $system=explode(“.”,$name); or the way I am passing the path to my image. This page helped
I am passing my images like this ./images/subfolder/image.jpg
The PHP explode function takes a string in this case my path and turns in into an array using the “.” as the cut off point so it was generating an array of
0 -
1 – /images/subfolder/image
2 – jpg
The thumbnail script looks at position 1 of the array for the file extension :-) so I changed all the $system1 with $system2 and it works fine now
February 7th, 2006 at 5:30 am
thanks a heapin helpin pardner
February 16th, 2006 at 12:14 pm
This article is very clear strutured and commented in a way that makes it most easy to understand how it works.
Thank you very much, that was exactly what I was looking for. I’m a professional software developer, but not much experienced with web development and I started using PHP yesterday, which means I still havn’t got much knowlede about the available functions in PHP.
Regards from Germany
Christian
March 1st, 2006 at 5:00 pm
Great script – saved me lots of time figuring out the details myself. Thanks!
Came across a couple of issues including the aspect ratio problem which I solved in a similar way to in the previous comment. Also, the problem with the “imagesx()imagesy()imagecopyresampled() and
imagedestroy() are not valid image resources” messages others have been getting. My solution to that was to simplify the script to only allow jpeg images. The first 3 lines of the function now read:
function createthumb($bigfilename,$thumbfilename,$new_w,$new_h){
$system=explode(‘.’,$bigfilename);
$src_img=imagecreatefromjpeg($bigfilename);
and simply check that the file was jpeg before continuing with:
if ($_FILES['imagefile']['type'] == “image/jpeg”){
// your code here
}
else {
echo “Not a jpeg”;
}
Hope this helps someone.
July 9th, 2006 at 7:52 am
Like many others I was looking for a simple script – potentially yours was it and I appreciate you publishing it, however I ended up spending a lot of time ‘fixing’ it :^( – shame about that, if you are going to leave it on your site perhaps you’d do well to fix it?
Edit: How about you tell me what the fixes are? It works fine here…
August 9th, 2006 at 2:34 pm
Warning: imagejpeg(): Unable to open ‘tn_2006-08-08-1.jpg’ for writing in /home/lostmin/public_html/df/screenshots/RPGVault/2006-08-08/thumbnail_generator.php on line 64
Also, is there a way it can automatically recurse all subdirectories creating thumbs for the pictures in each as it goes? because i have my images sorted into multiple folders
email if anyone has any ideas how to get this working
August 9th, 2006 at 2:36 pm
Warning: imagejpeg(): Unable to open ‘tn_2006-08-08-1.jpg’ for writing in /home/lostmin/public_html/df/screenshots/RPGVault/2006-08-08/thumbnail_generator.php on line 64
Also, how can i make it recursive subdirectories while it’s making thumbs?
if anyone has any ideas toss me an email krush@lostminions.org
August 12th, 2006 at 11:29 pm
Thumbs size isn’t scalled correctly.. example: from image 2592×1944 and new width set to 100px, and max height as 80px, you’re generating picture 100×60, but should be 100×75.
Here is code to scalling correctly:
if ($old_x >= $old_y)
{
$thumb_w = $new_w;
$ratio = $old_y / $old_x;
$thumb_h = $ratio * $new_w;
} else
if ($old_x < $old_y)
{
$thumb_h = $new_h;
$ratio = $old_x / $old_y;
$thumb_w = $ratio * $new_h;
}
Greets
September 11th, 2006 at 10:12 am
how can I filter out the new images in a directory to make a thumbnail?
September 23rd, 2006 at 5:52 pm
Does anyone know of a way of improving the quality of the thumbnails that this script creates? I’ve tried adding:
$jpeg_quality = 100;
then later on:
imagejpeg($dst_img,$filename,$jpeg_quality);
But the thumbnails still show a lot of JPEG artifacts…
Any help much appreciated.
Thanks
OP
October 13th, 2006 at 9:06 am
I too received the error message about system resources:
Warning: imagecreatefromjpeg(n-015 pendant 15.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in /home/site/public_html/thumbnailgen.php on line 46
Received same error for: imagesx, imagesy, imagecopyresampled, and imagedestroy.
Thanks in advance…
I’m new at this and didn’t quite understand how folks resolved this issue. Thanks in advance.
October 16th, 2006 at 1:29 am
I am having an issue that when the original image is smaller than the desired thumb it creates a black/blank image. How can I make the GD pick up that the image is smaller and create a copy of the existing image as the new one? I am using this code Function.
function createthumb($name,$filename,$new_w,$new_h)
{
$system=explode(“.”,$name);
if (preg_match(“/jpg|jpeg/”,$system2)){$src_img=imagecreatefromjpeg($name);}
if (preg_match(“/png/”,$system2)){$src_img=imagecreatefrompng($name);}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y)
{
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y)
{
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y)
{
$thumb_w=$new_w;
$thumb_h=$new_h;
}
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if (preg_match(“/png/”,$system1))
{
imagepng($dst_img,$filename);
} else {
imagejpeg($dst_img,$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
November 30th, 2006 at 12:23 pm
Here is a simple way to do image stretching keeping the original aspect ratio, that will not stretch the image if it is smaller than the desired with.
if ($old_x < $new_w && $old_y < $new_y)
{
$thumb_w=$old_x;
$thumb_h=$old_y;
}
else if ($old_x > $old_y) {
$thumb_w=$new_w;
$thumb_h=$old_y*($new_w/$old_x);
}
else if ($old_x <= $old_y) {
$thumb_h=$new_h;
$thumb_w=$old_x*($new_h/$old_y);
}
January 30th, 2007 at 11:24 pm
Is it possible to make a thumbnail – 150×150 px and then add another block of colour background beside?
The final image should end up as a 150×450 image, with the thumbnail image on the left and an empty block of colour to the right.
February 18th, 2007 at 5:29 pm
I have tried this script and I must say I like it. I have two problems though.
The first is that the aspect ratio is not correct. The thumbs it creates are skewed a bit. Not much, but enough to notice.
The second is that is resizing images BELOW the dimensions (800×600) I want. If I have a thumbnail already created at 100×150, the script resizes that also.
Is there a way to have the script not resize anything below a stated width and or height?
Thanks,
Frank
February 19th, 2007 at 7:05 am
The problem with using $system=explode(“.”,$file) and then referencing the extension by $system1 is that you are assuming there is only one period (.) in the filename. A much safer way would be to do the following…
$system = explode(‘.’, $somefile);
$total = count($system);
Now you can get your file extension from $system[$total-1] to be sure it’s the last element in the array.
March 23rd, 2007 at 4:06 am
I know that I’m probably suppose to put my folder names here, but where exactly in regard to the period – before, after or in place of?
$imagefolder=’.';
$thumbsfolder=’.';
Where should I place this script and how do I call it?
April 24th, 2007 at 10:43 pm
anyone have any ideas how to get this working in internet explorer???
April 27th, 2007 at 4:50 pm
I suggest replacing
$old_x = imageSX($src_img)
$old_y = imageSY($src_img);
with
list($old_x, $old_y, $type, $attr) = getimagesize($name);
as it does not have the overhead of using GD to get source image dimensions.
May 12th, 2007 at 5:32 pm
I have tried everything ive read in these comments and finally, no errors. Only problem now is the code isnt creating any thumbnails at all, rendering the code completely useless. The amount of trouble ive had with this code has lead me to belief it is bad code.
May 13th, 2007 at 12:14 am
i found that replacing imagecopyresampled by imagecopyresized ran much faster (thumbs are
not as pretty but still useful).
June 7th, 2007 at 6:14 pm
I respect those who offer free code to help the rest of us out. Thanks, I did however change something for a bit of added security:
$system=explode(‘.’,$name);
To:
$img_mime = getimagesize($name);
$system = $img_mime2;
Just in case someone renames say “moonlightlake.jpg” to “moonlightlake.png”
It help and give me a little peace of mind.
June 14th, 2007 at 9:02 pm
First of all thank you very much for your script. Thanks for sharing a simple and easy to understand, solution to all of us who don’t want to fuss with image editting software.
its very practical to use.
I have some questions though… I was trying to implement a if statement that checks if the tn_some-pic.jpg already exists so it doens’t need to create that one again.
because it will take forever to generate a quite amout of pictures when I only added a couple of them new.
I am beeing unssucessfull tho, and thought I could come and ask for some advice.
cheers!
July 3rd, 2007 at 1:36 pm
I have a similar problem to Fish above in that I’m getting black images instead of the image that was to be resized.
Also it works on one server (my hosting) but not another (my clients), any ideas?
July 5th, 2007 at 2:52 pm
i’ve tried using all of the codes here, but i still get the black thumbnail thing.
anyone could help me?
thank you.
*this is my code.(i already tried to change it according to some suggestions stated above, but i still get the black thumbnail.
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if ($old_x > $old_y) {
$thumb_w = $new_w; $thumb_h=($new_w/$old_x)*$old_y;
}
if ($old_x < $old_y) {
$thumb_w=($new_h/$old_y)*$old_x;
$thumb_h = $new_h;
}
if ($old_x == $old_y) {
$thumb_w = $new_w;
$thumb_h = $new_h;
}
August 16th, 2007 at 7:43 am
The problem with the black thumbnails lies in the fact that the php functions are written in some mad title-case. Therefore, all the function is returning is a basic true color image to the size specified, and the actual image is therefore not being used at all. All functions it appears must be written in lowercase, as this seems to be the convention with the php version that I am using (5.20). That sorted me out anyway!
Cheers,
Pete
August 25th, 2007 at 9:20 pm
Set everything to lowercase and still get black images, has anybody a solution
September 16th, 2007 at 5:34 pm
$thumbsfolder is declared but not used.
October 16th, 2007 at 5:36 am
$thumbsfolder variable should be added in the imagejpeg and imagepng functions and should be referenced like:
imagejpeg($dst_img,$GLOBALS['thumbsfolder'].$filename);
so the thumbs are produced in the correct folder. Still struggling with the “black rectangles” output issue.
January 22nd, 2008 at 12:08 am
I found your tutorial very simple and perfectly understadable.
I had almost everything working on my system until I found yours. I didn’t know of the resample tool. I know everything working and with some improvements like:
if (!file_exists($thumbnails_dir.$tb_name))
createthumb($pictures_dir.$name, $thumbnails_dir.$tb_name);
so it doesn’t create the file all the time. And a generator on my upload system so it doesn’t need to generate any time. But it’s the same.
Thank you.
February 2nd, 2008 at 5:50 pm
A tip is to use add option i to the preg_match expression to get a match of both jpg and JPG. I found that my digital camera saves the filenames in uppercase. The lines to open the file will be like this:
if (preg_match(“/jpg|jpeg/i”,$system1)){$src_img=imagecreatefromjpeg($name);}
if (preg_match(“/png/i”,$system1)){$src_img=imagecreatefrompng($name);}
February 19th, 2008 at 9:56 am
Hi!
i think this is exactly what i’m looking for. but it seems i can’t get it to work.
instantly it began to give me errors.
the error i’m struggling with is:
i get the following error:
Fatal error: Call to undefined function directory() in E:\websites\personeelsapplicatie\personeel\collegadata.php on line 162
what does this mean? it can’t read my directory, or the code? i’m hopeless.. please help me out!
ps. tnx for sharing this code, if it works i’ll come back to thank you :)
February 19th, 2008 at 9:57 am
the code, as it is not shown above…
$imagefolder=’./personeelsapplicatie/images/personeel/’;
$thumbsfolder=’./personeelsapplicatie/images/personeel/’;
$pics=directory($imagefolder,”jpg,JPG,JPEG,jpeg,png,PNG”);
$pics=ditchtn($pics,”tn_”);
if ($pics0!=”")
{
foreach ($pics as $p)
{
createthumb($imagefolder . $p,$thumbsfolder . “tn_”.$p,90,90);
}
}
May 14th, 2008 at 6:00 pm
Chris,
Thank you for making this available, with a couple of tiny tweaks to fit it to my particular setup (mostly in the configuration variables you provided at the top of the script), this worked perfectly and saved me a bunch of time generating the thumbnails locally and uploading them.
I like your coding style – very readable and easy to use, nice one.
Peter.
May 14th, 2008 at 6:10 pm
thanks for the script. very useful.
my one critical piece of feedback is regarding the lack of update of your tutorial. a number of bugs has been pointed out, but none of this info has been implemented in the article. as a result I (and probably many more) invented the wheel once again.
so, please update the article!
May 20th, 2008 at 1:58 pm
This script works like a charm… THANKS! One question. The imagejpeg function seems to make thumbnail files that are undeletable on my server (except by root). I get “Permission Denied”. Definitely a permissions or user problem. I’ve added a chmod command directly after the imagejpg command (tried 777 and 755). The script is making files as nobody which I can typically delete but for some reason the thumbs I cannot. I dont want to use chown since I dont now on which site this will be run and can’t pre-meditate the user. Any ideas what could be happeneing? THANKS in advance!
June 5th, 2008 at 4:18 pm
Andyc – that ‘check for jpg’ routine will not work for IE7. You have to check for all the mime types set for jpg, and they’re not all “image/jpeg”. Also check for “image/jpg” and “image/pjpeg” (progressive jpg).
June 8th, 2008 at 6:57 pm
This is a great script, but when I try to use it in the batch mode, it just stops running. I have a folder with about 300 images that I’m trying to thumbnail. No matter what I do, it will only create about 60 thumbnails. If I do a print_r on the array, all the images are there, so I know that it’s loading everything. A few echos show that on the last image that it “processes,” it never executes the imagecreatefromjpeg(). If I take out all the echos and run it, I get a 500 error from my server. I’m using 1and1 as my host if it helps.
Any ideas?
June 12th, 2008 at 3:43 pm
Hi,
First the function was not working for me until:
i) I separated the image extension beforehand and send it as a seperate argument “$extension= strtolower(strrchr($filename, ‘.’));”.
ii) I replaced “preg_match(‘/jpg|jpeg/’,$system1)” with “(($ext==’.jpg’)||($ext==’.jpeg’))” and so for the other image types.
Now the code seems to be working.
(Bad Luck for me as I discovered its a shared server without any write permissions :( )
July 21st, 2008 at 4:09 pm
this works fine but ANY IMAGES BIGGER THAN 4500 BY 2000 (there abouts) it will not work it works for huge images like 15meg files but not for images with large dimensions (no idea why this is )
any help would be much appricated.
July 21st, 2008 at 4:12 pm
also i thought i would add the error i receive is an error 500
July 22nd, 2008 at 6:27 pm
there’s a liuttle bug on your code. If out the full path on the $name it will not work, because the first explode will separate the image in the point as in
“www”, “example”,”com/myimage”,”jpg”
and will not hterefore recognize if it’s a jpg or a png. I changed the first line to
$system=explode(‘.’,substr($name, -4));
and now it works fine
October 24th, 2008 at 10:25 am
I had the problem of having incorrect aspect ratios during resizing. I made a correction, you can see below and Fish’s comment on October 21st, 2005 at 2:02 am also corrects the resizing mistake which is same correction as I have done below.
if ($old_x > $old_y)
{
$thumb_w=$new_w;
$thumb_h=$old_y*($new_w/$old_x);
}
if ($old_x < $old_y)
{
$thumb_w=$old_x*($new_h/$old_y);
$thumb_h=$new_h;
}
kind regards
October 30th, 2008 at 2:04 pm
Thank you so much for sharing your thumbnail generator. I really learned a lot by your explanations.
I also apriciate your good writing, because I used googles translator, to turn it in to danish.
October 30th, 2008 at 10:30 pm
I too had the problem with black images because the files I used the script on was named with .JPG instead of .jpg. To solve the problem i placed:
if (preg_match(“/jpg|jpeg/”,$system1)){$src_img=imagecreatefromjpeg($name);}
if (preg_match(“/png/”,$system1)){$src_img=imagecreatefrompng($name);}
with
if (preg_match(“/jpg|jpeg/”,$system1)){$src_img=imagecreatefromjpeg($name);}
if (preg_match(“/png/”,$system1)){$src_img=imagecreatefrompng($name);}
if (preg_match(“/JPG|JPEG/”,$system1)){$src_img=imagecreatefromjpeg($name);}
if (preg_match(“/PNG/”,$system1)){$src_img=imagecreatefrompng($name);}
December 10th, 2008 at 2:30 am
the code is good!!!
// bug corrections: directories can has character (point) , function explode() lose “.jpg” extension
$tmpname=basename($name);
$system=explode(‘.’,$tmpname);
February 2nd, 2009 at 6:37 am
I’m not a very good programmer, but for me, the script worked just fine on the first try. The problem I have, is getting the thumbnails to automatically output to a formatted page, so I can just load the photos to a folder online, and let Mr. PHP do the rest. I have NO idea how to do that.
Like I said– I’m not a very good programmer.
February 23rd, 2009 at 4:39 pm
Just an idea as far as validating the image. Depending on explode() to find the filetype could run into problems in very rare situations.
I used instead if(exif_imagetype($fileName) == IMAGETYPE_GIF) //works in php 4.3+
and if(exif_imagetype($fileName) == IMAGETYPE_JPEG)
exif_imagetype validates the image more effectively and prevents bugs if the script is processing a file with the .jpg extension, which isn’t actually a jpg.
More info can be found in the php manual here:
http://us.php.net/manual/en/function.exif-imagetype.php
March 10th, 2009 at 4:00 pm
Great code. Saved me a lot of time. … thanks for sharing!
Just to mention it. in thumbnail_generator.php on line 10:
createthumb($p,”tn_”.$p,150,150); should be createthumb ‘pics/’.$p,’thumbs/tn_’.$p,200,200); in order to create image thumbnails in thumbs folder.
and images with upercase
in order to
April 2nd, 2009 at 6:47 pm
Hi
Thanks for this script; but, I don’t down if another people had the same probleme than me :
When i wrote : createthumb(‘./xxx.jpg’,’./tn_xx.jpg’,100,100);
it don’t work if I don’t add a “.” in $system :
$system=explode(‘./’,$name);
After that, all run good
erf, another person wrote this … :D
THANK YOU !
April 6th, 2009 at 10:59 pm
Hey,
Thanks for the excellent tutorial, I got it working properly but I have a question. Let’s say I have a directory of images (of various sizes user uploaded). And then only display three of those images randomly on a page (I already have the random stuff done) My question is is I need to resize all of these images to 50×50 pixels only if they aren’t 50×50 pixels already. How can I detect the image size before I display the image:
I was thinking something like this:
if(imgWidth>50 || imgWidth>50){
createThumbnail()
}
else{
}
Is something like that possible, and would it interfere with page loading times very much. I’m thinking it will slow down the page load only the first time the page is loaded (when the thumbnails are created) is my thinking right?
May 5th, 2009 at 10:44 pm
I noticed a few PHP warnings, so I fixed this one. The original is on line #6 (commented-out):
//if ($pics0!=”")
if (is_array($pics))
August 14th, 2009 at 2:37 am
I have a small problem with this. I tried adding it to my image uploading script, so as the image was uploaded, a thumbnail would be created, but all I get is 100 × 100 black squares as thumbnails. I checked, and my images are uploading correctly, its just the thumbnails that are having the problem.
I tried:
@move_uploaded_file($_FILES["file"]["tmp_name"], “uploadedImages/” . $FileWithExtension);
createthumb($FileWithExtension,’thumbs/tn_’. $FileWithExtension,100,100);
And I tried:
@move_uploaded_file($_FILES["file"]["tmp_name"], “uploadedImages/” . $FileWithExtension);
createthumb($_FILES["file"]["tmp_name"],’thumbs/tn_’. $FileWithExtension,100,100);
And I tried:
@move_uploaded_file($_FILES["file"]["tmp_name"], “uploadedImages/” . $FileWithExtension);
createthumb(“uploadedImages” .$FileWithExtension,’thumbs/tn_’. $FileWithExtension,100,100);
Any help would be greatly appreciated.
October 9th, 2009 at 4:10 pm
How do I simple get the thumbnail extension “tn_” to be on the back of the original image name instead of the front so like instead of “tn_Filename.jpg” to “Filename_tn.jpg”
Any Ideas?
Great Appreciated.
October 30th, 2009 at 4:46 pm
Thank you so much! Your article about thumbnails was just what I needed!
November 11th, 2009 at 11:17 pm
From my point of view, $new_h and $new_w describe a rectangle in which the thumbnail should fit. So we shouldn’t really compare the original image dimensions, but the aspect ratios of the original image vs the max dimensions the user wants for the thumbnail.
if ($old_x/$old_y > $new_w/$new_h)
{
$thumb_w=$new_w;
$thumb_h=$new_w*$old_y/$old_x;
}
else
{
$thumb_h = $new_h;
$thumb_w=$new_h*$old_x/$old_y;
}
This creates corectly dimensioned thumbnails.
November 17th, 2009 at 12:42 am
I fixed the issue with the black thumbnails by changing the function createthumb as following:
line 39
if (preg_match(“/jpg|jpeg|JPG|JPEG/”,$system[count($system) - 1]))
I tried everything else and it was the only thing that worked for me.
Hope it helps!
March 23rd, 2010 at 6:43 pm
Bug Report:
First line of code on the thumbnail page:
Should be , you missed the semicolon or it was stripped out.
Hag
March 23rd, 2010 at 6:47 pm
Bug Report:
Poorly coded comment section.
Try to drop the generic stripslashes and add some logic in to prevent the hideous 1990′s drop type.
Hag
April 12th, 2010 at 3:08 pm
Great work! I love it. I dont know if anyone notice the issue with a file name with multiple “.” e.g ph.ot.o.jpg? It is a valid file name but the function will throw errors, because it is assumed that file names has only one “.” say photo.jpg.
To fix this I replaced $system0 with end($system). This will work even if the file name has 100 “.”s.