Archive for November, 2008

Thumbnailer

Wednesday, November 5th, 2008

This PHP script is a handy little tool to help dynamically create thumbnails. This will help your site look consistent and prevent you from having to upload or store multiple copies of an images.

First download the thumbnailer and upload it to a server that supports PHP and has the GD library enabled. For this post you will also need an image (GIF, JPG or PNG) that we can use to manipulate with the thumnbnailer. For this post will will use the following image as a testing image, make sure you slick the thumbnail below to get the full size image:

The thumbnailer.php file in a PHP script that kind of “tricks” the browser into thinking it is an image; so this file will be referenced as if it is an image using an html img tag. The thumbnailer.php file needs a few pieces of information, the first one being an image. For example lets assume that the thumbnailer.php file and the mexico.jpg image are in the same folder. To use the thumbnailer.php file with the mexico.jpg image the code would be:

<img src=”thumbnailer.php?file=mexico.jpg” />

Note: The file variable needs to be the image file name in relation to the thumbnailer.php file.

At this point the thumbnailer.php will load the mexico.jpg image and simply regurgitate it. If we want to resize it we need to provide the thumbnailer.php file with some more information. The thumbnailer.php file has two main algorithms to resizing an image.

Method One: maxwidth adn maxheight

The first method is by providing the thumbnailer.php file with a maxwidth and a maxheight. This method will resize the image within the provided dimension without losing original image dimension proportions.

For example the mexico.jpg image is about 800 pixels wide by 530 pixels high. If we wanted that image to fit within a 400 by 400 pixel space the code would be:

<img src=”thumbnailer.php?file=mexico.jpg&maxwidth=400&maxheight=400″ />

The image would be displayed as a 400 by 265 pixel image.

Method Two: width and height

The second method is to provide a width and height value. This method is similar to the above method except it will crop after resizing to force the image to be the exact dimensions. The image is crop instead of stretched so you don’t get people and things looking disproportionate.

<img src=”thumbnailer.php?file=mexico.jpg&width=200&height=200″ />

The above example woudl take the mexico image and crop a 530 by 530 pixel square out of the original image and then resize it to 200 y 200 pixels. This way you still see most of the image, not just a small 200 by 200 pixel closeup piece.