How to Resize Images (create thumbnails) using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to Resize Images (create thumbnails) using PHP

Post by Tony » Sun Nov 29, 2009 4:00 am

This script will take any image and automatically create a thumbnail of any size you want. The instructions for using this script are in the comment lines at the top of the script.

Code: Select all

<?php
// this script creates a thumbnail image from an image file - can be a .jpg .gif or .png file
// where $thumbsize is the maximum width or height of the resized thumbnail image
// where this script is named resize.php
// call this script with an image tag
// <img src="resize.php?path=imagepath"> where path is a relative path from the document root - such as subdirectory/image.jpg
$thumbsize = 200;
$imagesource = $_SERVER['DOCUMENT_ROOT']."/".$_GET['path'];
if (!file_exists($imagesource)) die();
$filetype = strtolower(substr($imagesource,strlen($imagesource)-4,4));
if($filetype == ".gif") $image = @imagecreatefromgif($imagesource); 
if($filetype == ".jpg") $image = @imagecreatefromjpeg($imagesource); 
if($filetype == ".png") $image = @imagecreatefrompng($imagesource); 
if (empty($image)) die();
$imagewidth = imagesx($image);
$imageheight = imagesy($image); 
if ($imagewidth >= $imageheight) {
  $thumbwidth = $thumbsize;
  $factor = $thumbsize / $imagewidth;
  $thumbheight = $imageheight * $factor;
}
if ($imageheight >= $imagewidth) {
  $thumbheight = $thumbsize;
  $factor = $thumbsize / $imageheight;
  $thumbwidth = $imagewidth * $factor;
}
$thumb = @imagecreatetruecolor($thumbwidth,$thumbheight);
imagecopyresized($thumb, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $imagewidth, $imageheight);
header("Content-type: image/jpeg");
imagejpeg($thumb);
imagedestroy($image);
imagedestroy($thumb);
?>
Post Reply

Return to “PHP & MySQL”