Advertisement
News

How to Dynamically Create Thumbnails

by

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.


Related Posts
  • Code
    WordPress
    An Introduction To Deploying WordPress with MinaImage400
    As a PHP application, WordPress is usually deployed by a very old method: uploading files via FTP. We have some deployment tools, but they often requires some type of Ruby skill. For example, one popular, powerful tool is Capistrano, but it's also very heavy with many Ruby/Rails related features. I also think that it's little bit tricky to install Capistrano for a PHP developer without any Ruby knowledge. So what options do we have as WordPress developers? In this tutorial, I will introduce you Mina: A small, light tool aims to fast deployment and server automation.Read More…
  • Code
    Web Development
    Laravel Unwrapped: Session, Auth and CacheLaravel wide retina preview
    Join me as we learn how to use Laravel's component-based system, Illuminate. Additionally, we'll see how to utilize service providers, Laravel's manager system, the Session, Auth, and Cache components, and the Store, Guard, and Repository libraries.Read More…
  • Computer Skills
    App Training
    Alfred Workflows for Advanced UsersAlfred400
    Well, you made it to the advanced tutorial. Well done! Now for the real work. Alfred can be used to do some complicated things, including recursive programming! The concepts here are not easy and not for the inexperienced programmer.Read More…
  • Code
    PHP
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
  • Code
    PHP
    Acceptance Testing With CodeceptionIntro to codeception retina preview
    Typically new features for web applications are tested by visiting the appropriate page in a browser, maybe filling out some form data, submitting the form, and then developers or testers hope to see their desired result. This is the natural way most web developers test their apps. We can continue with this natural testing process and improve upon it to ensure our apps are as stable as possible by using Codeception. Read More…
  • Code
    Plugins
    How to Create a WordPress Avatar Management Plugin from Scratch: Finishing TouchesPreview
    Avatar Manager for WordPress is a sweet and simple plugin for storing avatars locally and more. Easily. Enhance your WordPress website by letting your users choose between using Gravatar or a self-hosted avatar image right from their profile screen. Improved workflow, on-demand image generation and custom user permissions under a native interface. Say hello to the Avatar Manager plugin.Read More…