Here’s a very simple PHP class that i wrote to make thumbnail generation on JPG, PNG & GIF images really simple and painless.
NOTE: You will need to have GD installed on your server for this class to work!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
< ?php
	/**
	 * Image thumbnail generator
	 * Based on the work from http://sniptools.com/vault/generating-jpggifpng-thumbnails-in-php-using-imagegif-imagejpeg-imagepng
	 */
	class ThumbnailGenerator
	{
		public $sourceFile;
		public $destinationFile;
		public $width;
		public $height;
		public $format;
		public $scale;
 
		/**
		 * ThumbnailGenerator::__construct()
		 *
		 * @param mixed $sourceFile Path to source file
		 * @param mixed $destinationFile Path to destination file
		 * @param mixed $width Thumbnail file width
		 * @param mixed $height Thumbnail file height
		 * @param string $format jpeg, png or gif
		 * @param bool $scale Scale thumbnail
		 * @return
		 */
		public function __construct($sourceFile, $destinationFile, $width, $height, $format="jpeg", $scale=true)
		{
			$this->sourceFile = $sourceFile;
			$this->destinationFile = $destinationFile;
			$this->width = $width;
			$this->height = $height;
			$this->format = $format;
			$this->scale = $scale;
		}
 
		/**
		 * ThumbnailGenerator::generate()
		 *
		 * @return
		 */
		public function generate()
		{
			$fromFormat = "imagecreatefrom".$this->format;
			$sourceImage = $fromFormat($this->sourceFile);
			$sourceWidth = imagesx($sourceImage);
			$sourceHeight = imagesy($sourceImage);
 
			if($this->scale)
			{
				$ratio = $this->width / $sourceWidth;
				$this->width = $sourceWidth * $ratio;
				$this->height = $sourceHeight * $ratio;
			}
 
			$targetImage = imagecreate($this->width,$this->height);
			imagecopyresized($targetImage,$sourceImage,0,0,0,0,$this->width,
			$this->height,imagesx($sourceImage),imagesy($sourceImage));
 
			$imageFunction = "image".$this->format;
			return $imageFunction($targetImage, $this->destinationFile, 100);
		}
	}
?>

All credit goes to http://sniptools.com/vault/generating-jpggifpng-thumbnails-in-php-using-imagegif-imagejpeg-imagepng for the snippet!

Sample usage:

$tg = new ThumbnailGenerator("image.png", "thumbs/newimage.png", 100, 100, "png");
echo $tg->generate() ? "Thumbnail generated successfully" : "Failure!";