PHP Image Thumbnailer (GD)
Listed In PHP and MySQL » Images and GD — Viewing Full TutorialHey guys. Our aim here is to:
Make a script that resizes an image to a thumbnail size and keeps proportions
Adds a simple blue border
And.. learn a bit about the GD library.
You will need:
A server that has up tp date php and an up to date version of the gd library.
You can check this by running the following code in a .php document. jpg, png and gif support should all evaluate to true. If not, complain to your host!
If it does nothing but display its self glitchely to the browser, your host doesnt support php and you should buy some good hosting. free hosts are a good idea but in truth i havent seen one that doesnt suck.
<?php
print "<pre>";
print_r( gd_info() );
print "</pre>";
?>
if you want more information about the gd library after we are done go to >>the gd part of the php manua<<l. that said we should cover much of the basics in this tutorial, and more than most people will ever use.
We will call the image by putting thumb.php?f=file.png&s=OPTIONALmaxsize. (you can name the file what you want but thumb.php is logical. IT MUST BE A .PHP)
TUTORIAL
ok, to begin with i am going to show you the final code. this will give yuo time to try and digest the code yourself and if you are a scrounger who only wants the script, youll get it ;)
<?php
if (!isset($_GET['s'])){
$max = 150; //////this is your max size
} else {
$max = $_GET['s'];
};
//Check if the variables are set
if (!isset($_GET['f'])){
?> <hr />
<h2>You Must Set a File</h2>
thumb.php?f=FILENAMEHERE.png sets a file.
<hr />
<h2>Php Error:</h2>
<?php
break;
};
//retrieving file data
$filename = $_GET['f'];
//find image type
$namelength = strlen($filename);
$namelength = $namelength - 3;
if(strpos($filename, jpg) == $namelength){
$filetype = "jpg";
} else if(strpos($filename, png) == $namelength){
$filetype = "png";
} else if(strpos($filename, gif) == $namelength){
$filetype = "gif";
} else {
?> <hr />
<h2>The File You Selected (<?php print"$filename"; ?>) Isnt A Valid Type</h2>
It must be a gif, png or jpg.
<hr />
<h2>Php Error:</h2>
<?php
break;
};
//Check that the file actually exists
if ( !file_exists($filename) ) {
?> <hr />
<h2>The File You Selected (<?php print"$filename"; ?>) Doesnt Exist</h2>
As default it should be in the same directory as the thumbnailing file.
<hr />
<h2>Php Error:</h2>
<?php
break;
};
//setting sending as a png to the browser
header('Content-type: image/png');
//setting size values
list($width, $height) = getimagesize($filename);
if($width <= $max && $height <= $max){
$realwidth = $width;
$realheight = $height;
} else {
if($width >= $height){
$oldmax = $width;
} else if ($height > $width){
$oldmax = $height;
};
$decimal = $max / $oldmax;
$realwidth = $width * $decimal;
$realheight = $height * $decimal;
};
//creating thumbnail image
$thumb = imagecreatetruecolor($realwidth, $realheight);
//setting border color (the numbers are values from 0-255 in the order r, g ,b)
$color = imagecolorallocate($thumb, 0, 0, 200);
//detecting type of source file
if ( $filetype == "png") {
$source = imagecreatefrompng($filename);
} else if ( $filetype == "jpg") {
$source = imagecreatefromjpeg($filename);
} else if ( $filetype == "gif") {
$source = imagecreatefromgif($filename);
} else {
print"Error!";
break;
};
// resizing here
imagecopyresized($thumb, $source, 0, 0, 0, 0, $realwidth, $realheight, $width, $height);
//drawing border
$widthm1 = $realwidth - 1;
$heightm1 = $realheight - 1;
imageline( $thumb, 0,0, $widthm1, 0, $color);
imageline( $thumb, $widthm1, 0, $widthm1, $heightm1, $color);
imageline( $thumb, $widthm1, $heightm1, 0, $heightm1, $color);
imageline( $thumb, 0, $heightm1, 0, 0, $color);
//rendering new image
imagepng($thumb);
//destroying old data
imagedestroy($thumb);
imagedestroy($source);
?>
i will now try to cut this down into manageable chunks.
This is simply opening the php parser for use with a document. Remember the document also needs to be set as a .php
<?php
Here we set $max to be the default maximum size for the thumbnail. We then check if the variable $s (for Size) is set in the url (i.e. thumbnail.php?f=image.jpg&s=1000). if it is set the new size (in pixels) becomes the max size.
The max size is the size set to the longest size if the longest size is larger than the max. the rest of the image is kept in proportion.
if (!isset($_GET['s'])){
$max = 150;
} else {
$max = $_GET['s'];
};
Now we are looking for the essential variable ?f (for File). it should be set as such, thumbnailer.php?f=myimage.jpg you could append &s=1000 to the end of that url if you wanted to reset the max file size (as above).
if this variable is not set, we end the script and show the user how the error happened. (a php error is shown where you put break; in the script)
if (!isset($_GET['f'])){
?> <hr />
<h2>You Must Set a File</h2>
thumb.php?f=FILENAMEHERE.png sets a file.
<hr />
<h2>Php Error:</h2>
<?php
break;
};
Here we are setting the name of the image to the variable $filename.
$filename = $_GET['f'];
first we find the length of the string in the variable $filename, then we -3 from that number, so that we know how far into the name the filetype starts.
then we see if png, jpg or gif are in this position. (i would do bmp and tiff etc. but the gd library only supports jpg, png and gif. Be aware that .jpeg images will not work and should always be renamed to .jpg)
if the file isnt a jpg, png or gif, we end the script and explain why.
$namelength = strlen($filename);
$namelength = $namelength - 3;
if(strpos($filename, jpg) == $namelength){
$filetype = "jpg";
} else if(strpos($filename, png) == $namelength){
$filetype = "png";
} else if(strpos($filename, gif) == $namelength){
$filetype = "gif";
} else {
?> <hr />
<h2>The File You Selected (<?php print"$filename"; ?>) Isnt A Valid Type</h2>
It must be a gif, png or jpg.
<hr />
<h2>Php Error:</h2>
<?php
break;
};
Now we see if the file called $filename actually exists. if not we end the script and explain the error.
if ( !file_exists($filename) ) {
?> <hr />
<h2>The File You Selected (<?php print"$filename"; ?>) Doesnt Exist</h2>
As default it should be in the same directory as the thumbnailing file.
<hr />
<h2>Php Error:</h2>
<?php
break;
};
This part of the code sends a header to the browser saying that the data the script is sending will be a png. (this occurs even if the original image was a jpg or gif, because pngs are best allround.)
header('Content-type: image/png');
Take a minute to try and get your head around this. it involves some math (shock, horror).
first we list the values which the function getimagesize() produces from our $filename image. they are made into $width and $height. they contain the width and height of the original image in pixels. (if that wasnt obvious you should be shot)... (three times)... (or two if you have an IQ of less than 80)...
first we check if both width and height are less than or equal to $max. if they are both less than or equal to the max, there is no reason to downsize the image. so we set the final variables $realheight and $realwidth to the same sizes as the image.
Otherwise we check which of the variables $width or $height is bigger and set that size to the variable $oldmax (i.e. the old maximum size.)
We now set $decimal to be the number resulting from $max / $oldmax (i.e. if $max = 150 and $oldmax = 300, $decimal will be 0.5, i.e. the number that you have to times $oldmax by to get $max. because this is a variable decimal, not a set digit, it will work for $width and $height, bringing them both to below or at the $max. and it will keep the proportion.)
list($width, $height) = getimagesize($filename);
if($width <= $max && $height <= $max){
$realwidth = $width;
$realheight = $height;
} else {
if($width >= $height){
$oldmax = $width;
} else
if ($height > $width){
$oldmax = $height;
};
$decimal = $max / $oldmax;
$realwidth = $width * $decimal;
$realheight = $height * $decimal;
};
We are now making the canvas for the image, using the sizes set above. (imagecreate() does not produce a thumbnail with the true colors of the old image so we use imagecreatetruecolor())
$thumb = imagecreatetruecolor($realwidth, $realheight);
now we set the color that we want the 1 pixel border around the thumbnail to be. the numbers are values from 0-255 in the order r, g ,b for red, green, blue. i.e. 255, 0, 0 would make bright red. here we make a darkish blue.
$color = imagecolorallocate($thumb, 0, 0, 200);
A while back we set $filetype to the type of image we were using as a source. thereby we were able to filter out non-image files and non-supported image files.
now we use the same variable to tell php how to interpret the image. if we used imagecreatefrompng() on a jpg, it wouldnt work.
if ( $filetype == "png") {
$source = imagecreatefrompng($filename);
} else if ( $filetype == "jpg") {
$source = imagecreatefromjpeg($filename);
} else if ( $filetype == "gif") {
$source = imagecreatefromgif($filename);
} else {
print"Error! the file is probably invalid. FOOL.";
break;
};
Now we copy the old image $source to the new canvas $thumb, in the new size. this uses lots of old variables so should be easy to understand. the 0s in the middle are, i believe for positioning the image in the new canvas, but as we want our image to fill the whole canvas, and it is the right size, we have no problem.
imagecopyresized($thumb, $source, 0, 0, 0, 0, $realwidth, $realheight, $width, $height);
because the pixels in an image are read like a book, but numbered starting from 0, we need to subtract 1 from the heights and withes of the image to find the corner points in the image.
the imageline function is as such: imageline([canvas], [x axis position for starting pixel], [y axis position for starting pixel], [x axis position for ending pixel], [y axis position for ending pixel], [color of line])
we set $color a few blocks up.
$widthm1 = $realwidth - 1;
$heightm1 = $realheight - 1;
imageline( $thumb, 0,0, $widthm1, 0, $color);
imageline( $thumb, $widthm1, 0, $widthm1, $heightm1, $color);
imageline( $thumb, $widthm1, $heightm1, 0, $heightm1, $color);
imageline( $thumb, 0, $heightm1, 0, 0, $color);
we now render the image (as a png)
imagepng($thumb);
we destroy the old data for the two images we have worked on. we no longer need it.
imagedestroy($thumb);
imagedestroy($source);
and finally we close the php tag again
?>
we now take a deep breath. and were done!
ahhhh ///DONT ADD THIS TO YOUR CODE!
Just remember you cannot put any html or browser output before or after the code or it wont work.
comments more than welcome.
