Sometimes we need to deal with heavy images that could make page load to slow down. This PHP script will help you to easily process and scale down all images in a directory and its sub directories recursively. The script can very easily be ported to any PHP framework just inserting the functions in a class and calling them as showed here:
<?php
/**
* @copyright R. Elizondo
* @license propietary
*/
/**
* @param string $dir
* @return array
* @since 2023-09-15
*/
function getFilesRecursively(string $dir): array
{
$files = [];
// Check if the directory exists
if (is_dir($dir)) {
// Open the directory for reading
if ($dh = opendir($dir)) {
// Read directory entries
while (($file = readdir($dh)) !== false) {
// Skip "." and ".." entries
if ($file != '.' && $file != '..') {
$filePath = $dir . '/' . $file;
if (is_dir($filePath)) {
// Recursively get files from subdirectory
$files = array_merge($files, getFilesRecursively($filePath));
} else {
// Add the file to the list
$files[] = $filePath;
}
}
}
closedir($dh);
}
}
return $files;
}
/**
* @param string $imagePath
* @return bool
* @since 2023-09-15
*/
function processImageScaling(string $imagePath): bool
{
// Desired dimensions for the scaled image
$desiredWidth = 1080;
$desiredHeight = 720;
// Load the original image
$originalImage = imagecreatefromjpeg($imagePath);
if ($originalImage === false) {
die('Could not load the original image.');
}
// Get the original image's dimensions
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);
// Calculate the scaling factor
$widthRatio = $desiredWidth / $originalWidth;
$heightRatio = $desiredHeight / $originalHeight;
if ($widthRatio < $heightRatio) {
// Scale based on width
$newWidth = $desiredWidth;
$newHeight = round($originalHeight * $widthRatio);
} else {
// Scale based on height
$newWidth = round($originalWidth * $heightRatio);
$newHeight = $desiredHeight;
}
// Create a new image with the desired dimensions
$newImage = imagecreatetruecolor($newWidth, $newHeight);
// Perform the image copy and scaling
imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
// Save the scaled image, replacing the original
// you can save as any of supported image formats in GD library
if (imagejpeg($newImage, $imagePath, 90)) {
echo "Image scaled and saved successfully.\n";
} else {
echo "Error saving the scaled image.\n";
}
// Clean up resources
imagedestroy($originalImage);
imagedestroy($newImage);
return true;
}
// Directory to start the scan
$directory = __DIR__ . '/../images';
//Get the img files to process
$files = getFilesRecursively($directory);
// Process one by one
foreach ($files as $imagePath) {
echo 'Processing' . $imagePath . "\n";
if (file_exists($imagePath)) {
// Get image dimensions
list($width, $height) = getimagesize($imagePath);
if ($width === null || $height === null) {
echo 'Unable to get the image dimensions.';
} else {
echo "Image Width: $width pixels\n";
echo "Image Height: $height pixels\n";
//Process the image
if ($width>1080 || $height > 720) {
echo "requires scaling down \n";
$ok = $ok && processImageScaling($imagePath);
}
}
} else {
echo 'Image file does not exist.';
}
}
if ($ok) {
echo "\n\n";
echo "***************************************\n";
echo "*** Job completed successfully! ***\n";
echo "***************************************\n";
}