So I’ve set up this page to share pictures of my wifes miniatures and similar. The problem is that whenever the page loads, the image thumbnails don’t show
The problem was filesize. So I’ve updated my PHP so it automatically creates thumbnails the first time the page is loaded, and I’ve implimented lazy loading. this looks like this
<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
$gallery = isset($_GET['gallery']) ? $_GET['gallery'] : '';
$directory = __DIR__ . '/' . $gallery;
$thumbDirectory = $directory . '/thumbs';
// Function to create thumbnails
function createThumbnail($source, $destination, $thumbWidth) {
$img = imagecreatefromstring(file_get_contents($source));
$width = imagesx($img);
$height = imagesy($img);
$new_width = $thumbWidth;
$new_height = floor($height * ($thumbWidth / $width));
$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($tmp_img, $destination);
}
// Validate the gallery directory
if (is_dir($directory) && is_readable($directory)) {
// Ensure the thumbs directory exists
if (!is_dir($thumbDirectory)) {
mkdir($thumbDirectory, 0755, true);
}
// Get all files from the directory
$files = array_diff(scandir($directory), array('.', '..'));
// Generate thumbnails and get file modification times
$fileInfo = [];
foreach ($files as $file) {
if ($file != "thumbs" && !is_dir($directory . '/' . $file)) {
$sourcePath = $directory . '/' . $file;
$thumbPath = $thumbDirectory . '/' . $file;
// Create thumbnail if it doesn't exist
if (!file_exists($thumbPath)) {
createThumbnail($sourcePath, $thumbPath, 150); // 150px wide thumbnail
}
// Get file modification time
$fileInfo[] = ['file' => $file, 'mtime' => filemtime($sourcePath)];
}
}
// Sort files by modification time, newest first
usort($fileInfo, function($a, $b) {
return $b['mtime'] - $a['mtime'];
});
$sortedFiles = array_column($fileInfo, 'file');
} else {
$sortedFiles = [];
echo "<p>Invalid gallery specified or directory does not exist.</p>";
}
?>
this also sorts them newest first. not that that was an issue haha.