WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : Dynamic Thumbnail Generation
Categories : PHP, Graphics, GD image library
J. Thomas Enders
J. Thomas Enders
Date : 2003-11-28
Grade : 0 of 5 (graded 0 times)
Viewed : 25851
Search : More Articles by J. Thomas Enders
Action : Grade This Article
Tools : My Favotite Articles


  Submit your own code examples 
 


Abstract
This article covers the topic of dynamic thumbnail generation. The idea is that a user uploads a large image and then our program generates a thumbnail version of that large image. The examples in this article require that you have a version of php compiled with the gd library and are able to write to a directory on your server from within php.

Section I: Checking For Compatibility
If you are not sure you have the gd library installed it is very easy to check. There is a function in the gd library called gd_info. Just call gd_info() and if it throws an error then the gd library is not installed on your server. For more information about installing and configuring the gd library see here http://www.boutell.com/gd/.

There are a couple of ways you can check to see if php can write to files in a directory. If you have ftp access you can probably just set permissions on a directory to global read write which will allow php to write to files in that directory. The other way is to use one of the examples from here, http://www.php.net/manual/en/features.file-upload.php, and see if it throws errors.

Section II: Uploading The File
Uploading the graphic requires a couple of steps. First you have to create an html form that allows the user to upload a file. The form looks like this:


<form action="<?=$_SERVER["PHP_SELF"]?>" method=post enctype="multipart/form-data">
Select A File To Upload: <input type="file" name="image_file"><br>
<input type="submit" name="submitter" value="Upload File">
</form>


There are two important things about this form that allow it to upload files. The first is the enctype parameter of the form tag. Setting the enctype to multipart/form-data lets the web server know that this form may contain binary data along with it so that the data can be parsed properly. The second aspect is the type=”file” parameter of the input tag. This tells the browser to put a button up so that the user can select a file from their hard drive and then transmit that file as binary data.

Now that we have used HTML, more specifically the http protocols, to send our file to the server we have to process the file with php. For our purposes this consists of moving the file from its temporary position to its final resting place. This is done with the following code:


<?
if(is_uploaded_file($_FILES['image_file'])) {
if(!@
move_uploaded_file($_FILES['image_file']['tmp_name'], 'my_dir/' . $_FILE['image_file']['name'])) {
die(
"***ERROR: Could not copy the upload file.<br />\n");
}
//end if
} //end if
?>




This code does a couple of important things. The first line makes sure that the file was uploaded successfully. The second line uploads the file and also checks to make sure that the copy is successful. The code inside the second if statement just displays an error message and halts the script.

Section III: Getting The Image Into PHP
Now that the file is on the server and copied into is permanent directory we have to load the file into php so that we can manipulate it. This is done like this


<?
$im_file_name
= 'my_dir/' . $_FILES['image_file']['name'];
$image_attribs = getimagesize($im_file_name);
$im_old = imageCreateFromJpeg($im_file_name);
?>


This code may look simple but it is doing quite a bit. The first line is just putting the path to and name of the file all together in an easier to type variable name. The second line reads the attributes of the file; height, width, image type and the height width string for the img tag in html; and stores them in an array. The last line actually reads the image into php. This function creates an image object from a jpeg image.

Section IV: Setting Up The Thumbnail Object
The next thing we have to do is setup a second image object that will be the thumbnail. This is done with this code:


<?
$th_max_width
= 144;
$th_max_height = 144;
$ratio = ($width > $height) ? $th_max_width/$image_attribs[0] : $th_max_height/$image_attribs[1];
$th_width = $image_attribs[0] * $ratio;
$th_height = $image_attribs[1] * $ratio;
$im_new = imagecreatetruecolor($th_width,$th_height);
imageAntiAlias($im_new,true);
?>


This code is pretty straight forward. The first two lines set up the maximum size of our thumbnail for height and width, in this case 144 pixels or 2 inches. The next line is very important; it uses the height or width, depending on orientation, of the original file to calculate that ratio to resize the image by. The next two lines calculate the actual size of the thumbnail from the resize ratio and the original image. We calculate the size of the thumbnail in this manor to avoid skewing of the image when we resize it. The next line creates a truecolor image object that is the size of our thumbnail. The last line makes the newly created image object antialiased.

Section V: Resize The Original Image And Write It To Disk Believe it or not the hard work is done and the remaining work is done in three lines of code. These three lines:


<?
$th_file_name
= 'my_dir/thumbs/' . $_FILES['image_file']['name'];
imageCopyResampled($im_new,$im_old,0,0,0,0,$th_width,$th_height, $image_attribs[0], $image_attribs[1]);
imageJpeg($im_new,$th_file_name,100);
?>


The first line of code just sets up the name of our thumbnail image. The second line of code copies the original image into the thumbnail image and resizes it. All those zeroes just tell the function to start in the upper left hand corner of both images. The next four parameters tell the function to stop at the lower right hand corner of both images. In other words we want to copy and resize the entire first image into the entire second image. The last line creates a jpeg file on the server from the image object.

That is all there is to it. We have now dynamically created a thumbnail image.

Section VI: Other Resources And Continued Reading









An intro to using the GD image library with PHP
Categories : PHP, GD image library, Graphics
Generating Images on the Fly With PHP
Categories : PHP, Graphics, GD image library
Saving Images in MySQL
Categories : MySQL, PHP, Graphics, Databases
Working with Dates and Times in PHP
Categories : PHP, Date Time
10 PHP Functions I Bet You Didn't Know About!
Categories : PHP, PHP Functions, Filesystem, Arrays, Errors and Logging
Date Arithmetic With MySQL
Categories : PHP, Databases, MySQL, Date Time
Using the .NET Assembly in PHP
Categories : PHP, .NET
Aspect-Oriented Programming and PHP
Categories : PHP, Aspect Oriented Programming
PHP References Explained
Categories : PHP References, PHP
Beginners guide to PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, Installation
Logging with PHP
Categories : PHP, Log Files
Building A Persistent Shopping Cart With PHP and MySQL
Categories : PHP, MySQL, Databases, Ecommerce
Who's Linking?
Categories : PHP, Beginner Guides, To PHP
Generating One-Time URLs with PHP
Categories : PHP, URLs
Creating Auto-incrementing ID Fields with PHP and Oracle
Categories : PHP, PHP options/info, Databases, Oracle
Mads Rasmussen wrote : 384
your proportion calculations are wrong.

conditional ternary expression should depend on max width
and max height and not on old image proportions.

ex.

$ratio = ($max_x < $max_y)? $max_x / $old_x : $max_y /
$old_y;
$new_x = $old_x * $ratio;
$new_y = $old_y * $ratio;

try it out for yourself.


Mads Rasmussen wrote : 385
disregard my last comment!, your calculations are accurate for
that purpose. My bad.