Have you ever needed to create thumbnails when working with PHP? This handy function will help do the job!
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 | function createThumbnail($src, $dest, $desiredWidth, $desiredHeight, $fileName, $fileType) { // Read the source image. switch ($fileType) { case "jpg": case "jpeg": $sourceImage = imagecreatefromjpeg($src); break; case "png": $sourceImage = imagecreatefrompng($src); break; case "gif": $sourceImage = imagecreatefromgif($src); break; } // Get the source image size. $width = imagesx($sourceImage); $height = imagesy($sourceImage); if ($width > $height) { $desiredHeight = floor($height * ($desiredWidth/$width)); } if ($height > $width) { $desiredWidth = floor($width * ($desiredHeight/$height)); } // If the source image size is bigger than the desired size, crop it. if ($width > $desiredWidth || $height > $desiredHeight) { // Create the virtual image. $virtualImage = imagecreatetruecolor($desiredWidth, $desiredHeight); // Create a copy of the source image at its desired size. imagecopyresampled($virtualImage, $sourceImage, 0, 0, 0, 0, $desiredWidth, $desiredHeight, $width, $height); // Create the physical thumbnail in the desired destination. switch ($fileType) { case "jpg": case "jpeg": return imagejpeg($virtualImage, $dest.$fileName.'.'.$fileType); break; case "png": return imagepng($virtualImage, $dest.$fileName.'.'.$fileType); break; case "gif": return imagegif($virtualImage, $dest.$fileName.'.'.$fileType); break; } // If the source image is smaller than the desired image, don't resample just copy the image to the desired destination. } else { copy($src,$dest.$fileName.'.'.$fileType); } } |
When calling this function, you need to pass in the following arguments:
- $src – The source is the path to the image you want to create a thumbnail of.
- $dest – The destination is the path to where you want to save the thumbnail.
- $desiredWidth – The desired width is the width in pixels you want the thumbnail to be.
- $desiredHeight – The desired height is the height in pixels you want the thumbnail to be.
- $fileName – The file name is the name you want the thumbnail to have.
- $fileType – The file type is the type of image the thumbnail should be.