Try Tuts+ Premium, Get Cash Back!
how to dynamically create thumbnails
videos

How to Dynamically Create Thumbnails

In this week’s screencast, I’ll show you how to upload files and then have PHP dynamically create a thumbnail. Whether you’re building an ecommerce site, or just a simple gallery, these techniques will absolutely prove to be useful. If you’re ready for your “spoonfed” screencast of the week, let’s get going!

*Note – There have been a few slight changes to the code after some additional thinking and some great suggestions. Don’t worry, very little has changed. Just some cleanup. You can review the changes below, and/or download the source code.

The Simple Config File

The first step is to create a simple config file where we can store a few variables. By placing these in their own file, we can easily make changes to our code without having to edit many lines.

$final_width_of_image = 100;
$path_to_image_directory = 'images/fullsized/';
$path_to_thumbs_directory = 'images/thumbs/';
  • $final_width_of_image – This variable will store the width of our thumbnail.
  • $path_to_image_directory – This stores the path to our full sized images folder
  • $path_to_thumbs_directory – This stores the path to our full thumbnails directory

Save this file as ‘config.php’ and place it in the root of your folder.

The HTML

Screenshot

Next, create a new page called “index.php” and paste the following.

<?php

require 'config.php';
require 'functions.php';

if(isset($_FILES['fupload'])) {
	
	if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name'])) {
		
		$filename = $_FILES['fupload']['name'];
		$source = $_FILES['fupload']['tmp_name'];	
		$target = $path_to_image_directory . $filename;
		
		move_uploaded_file($source, $target);
		
		createThumbnail($filename);		
	}
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
	<meta name="author" content="" />
	<title>Dynamic Thumbnails</title>
</head>

<body>
	<h1>Upload A File, Man!</h1>
	<form enctype="multipart/form-data" action="" method="post">
		<input type="file" name="fupload" />
		<input type="submit" value="Go!" />
	</form>
</body>
</html>

First, scroll down a bit to the body tag. To keep things as bare-bones as possible, I’ve created an extremely simple form. But it will get the job done just fine.

<form enctype="multipart/form-data" action="" method="post">
  <input type="file" name="fupload" />
  <input type="submit" value="Go!" />
</form>

Any time that you’re going to be working with the “file upload” input type, you need to add an “enctype” attribute to the form tag.

<form enctype="multipart/form-data"

Rather than posting to a different page, we’ll just write the code in our main document. To do that, we’ll set the action attribute equal to this page.

action="<?php print $_SERVER['PHP_SELF']

Now, scroll back up to the PHP code at the top. We’re requiring two files. The first is the config file that we just created. The second one is “functions.php” – which we’ll create shortly.

Next, we’re checking to see if the page has posted back. If it has, we’ll then check to see if the file that the user chose was either a “jpg”, “gif”, or “png”. We can do this by checking the file name against a regular expression.

if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name']))

To learn more about regular expressions, watch this screencast.

Moving along, we’re creating a few variables.

  • $filename - Stores the name of the file that the user has chosen to upload.
  • $source – When the submit button is clicked, the file will be saved into a temporary directory. This variable will store that path.
  • $target – This will store the path of where the uploaded image should be saved.

Saving the File

The final step is to move the file from the temporary directory into our “images/fullsized” folder. We can do this by calling the move_uploaded_file() function. We’ll pass in two parameters. The first one needs to know the path to the temporary folder. The second needs to know where to save the file. ($source and $target, respectively)

move_uploaded_file($source, $target);

Creating the Thumbnail

Rather than store all of the code in our index.php page, let’s create another page called “functions.php”. Create and open this new file and write a new function called “createThumbnail()”.

function createThumbnail($filename) {
	
	require 'config.php';
	
	if(preg_match('/[.](jpg)$/', $filename)) {
		$im = imagecreatefromjpeg($path_to_image_directory . $filename);
	} else if (preg_match('/[.](gif)$/', $filename)) {
		$im = imagecreatefromgif($path_to_image_directory . $filename);
	} else if (preg_match('/[.](png)$/', $filename)) {
		$im = imagecreatefrompng($path_to_image_directory . $filename);
	}
	
	$ox = imagesx($im);
	$oy = imagesy($im);
	
	$nx = $final_width_of_image;
	$ny = floor($oy * ($final_width_of_image / $ox));
	
	$nm = imagecreatetruecolor($nx, $ny);
	
	imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
	
	if(!file_exists($path_to_thumbs_directory)) {
	  if(!mkdir($path_to_thumbs_directory)) {
           die("There was a problem. Please try again!");
	  } 
       }

	imagejpeg($nm, $path_to_thumbs_directory . $filename);
	$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
	$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a 	  thumbnail has been created.';
	echo $tn;
}

We’ll start by requiring the “config.php” file once again. Next, we’ll check to see whether the user selected a “jpg”, “gif”, or “png”. We must do this because PHP requires a different function depending on the file: “imagecreatefromjpeg”, “imagecreatefromgif”, “imagecreatefrompng”.

imagecreatefromjpeg

After that, we must store the width and height values of the image that the user chose to upload. We can do this by calling “imagesx”, and “imagesy”, respectively.

$ox = imagesx($im);
$oy = imagesy($im);

Next, we’ll create two more variables that will store the width and height values for the thumbnail that will soon be created.

  • $nx – is equal to the value from our config file: 100
  • $ny. We’ll need to run some simple math to find the correction proportionate height.
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));

ImageCreateTrueColor

imageCreateTrueColor

In our case, we’re passing in the “$nx”, and “$ny” variables that we just created.

Image Copy Resized

imagecopyresized
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);

Saving the Thumbnail

The final steps require that we check to see if a “thumbnails” folder exists. If it doesn’t, we’ll create it by using “mkdir”. Then, we’ll output our new image to the thumbnails folder.

if(!file_exists($path_to_thumbs_directory)) {
  if(!mkdir($path_to_thumbs_directory)) {
      die("There was a problem. Please try again!");
  } 
}
imagejpeg.png

Finally, we need to echo out the thumbnail to show the user that his image was uploaded successfully.

$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a 	  thumbnail has been created.';
echo $tn;

Finished

Well done! This screencast was somewhat hastily done – because of time constraints. You might want to clean up the code a bit and a bit more error handling.

If you wish to take things further, see if you can figure out how to crop the images as well! As always, I’m more than open to refinement and suggestions!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Tags: Videos
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pingback: 用PHP实现Instagram滤镜效果 | 灵梦程

  • Drew Dyer

    Hey Jeffery,

    I know this is an old tutorial, but would you mind to share how to add random numbers to the beginning of the filename. I’m sure this is easy, but man am I stuck.

    I would greatly appreciate your help.

    Thank you!

    • HelpIt

      Change the line:

      imagejpeg($nm, $path_to_thumbs_directory . $filename);

      To:

      $filename = time() . ‘_’ . $filename;
      imagejpeg($nm, $path_to_thumbs_directory . $filename);

      This will add a timestamp to the front of the image, ensuring that it the file is unique.

  • http://riseit.com mukesh

    please help me
    You don’t have permission to access /Thumbnails/<!– on this server.

  • http://risetechnologies.in mukesh

    am getting this error even though i change entire wamp server file properties its not working

    Forbidden

    You don’t have permission to access /Thumbnails/ <!– on this server.]

    plz help me

  • SimoLab

    Thanks for the great tutorial.
    But there is a serious security problem with your file type filtering. you used regular expression to filter file types by extension BUT don’t forget that i can change an extension of php shell to a .png and then i can upload it to the server, after upload finish i can use an HTTP replay tool ( so many extensions for firefox and other browsers are available) to change the fake .png extension back to .php and then i can execute the shell and take full control of the server.
    to avoid this you need to use file type magic numbers as a second filter to be sure that it’s a real image file and not a fake hidden dangerous file.

  • Kamlesh Khatti

    Create thumbnail image by php
    When we upload large size images on server. Uploaded large images take more time to load on webpage, so we need to show small size images on our webpage. Image thumbnail is a solution to generate uploaded image’s thumbnail to show required size images on our website.
    http://codelibrary.googleplus.co.in/create-thumbnail-image-by-php/