Last active
April 19, 2022 09:23
-
-
Save beporter/45f16185e2fe8f186e29 to your computer and use it in GitHub Desktop.
A quick PHP script to generate a folder of thumbnails from a source folder of JPG image files. PHP must be able to write files to the local directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Make sure we see processing errors during development/testing. | |
error_reporting(E_ALL); | |
ini_set('display_errors', true); | |
// Set up operating parameters. | |
$filePattern = 'gallery/*.[jJ][pP][gG]'; | |
$thumbPattern = 'thumbs/%s'; | |
$targetWidth = 200; | |
$targetQuality = 80; | |
// Create the output dir, if it doesn't already exist. This will fail | |
// if PHP does not have write access to the local folder. | |
$thumbDir = sprintf($thumbPattern, ''); | |
if (!is_dir($thumbDir)) { | |
mkdir($thumbDir); | |
} | |
// Abort if GD is not installed. | |
if (!function_exists('imagejpeg')) { | |
die('PHP does not have the GD extension installed. Aborting.'); | |
} | |
// Abort if the output directory is not writable. | |
if (!is_writable($thumbDir)) { | |
die('The output directory is not writable by PHP. Check permissions. Aborting.'); | |
} | |
// Loop over all found jpg files. | |
foreach (new GlobIterator($filePattern) as $f) { | |
// var_dump($f->getRealpath()); // Debugging the path name. | |
// Skip regenerating cached thumbs for performance. | |
$thumbPath = sprintf($thumbPattern, $f->getFilename()); | |
if (file_exists($thumbPath)) { | |
continue; | |
} | |
// Determine thumbnail output size. | |
list($w, $h) = getimagesize($f->getRealpath()); | |
$ratio = $h / $w; | |
$targetHeight = round($targetWidth * $ratio); | |
// Generate the thumbnail from the original. | |
$jpg = imagecreatefromjpeg($f->getRealpath()); | |
$thumb = imagecreatetruecolor($targetWidth, $targetHeight); | |
$success = imagecopyresampled( | |
$thumb, | |
$jpg, | |
0, 0, 0, 0, | |
$targetWidth, $targetHeight, $w, $h | |
); | |
imagejpeg($thumb, $thumbPath, $targetQuality); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See here: https://stackoverflow.com/a/32848242/70876