Skip to content

Instantly share code, notes, and snippets.

@beporter
Last active April 19, 2022 09:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save beporter/45f16185e2fe8f186e29 to your computer and use it in GitHub Desktop.
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.
<?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);
}
@beporter
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment