diff --git a/public/index.php b/public/index.php index 51949c1..80c8d21 100644 --- a/public/index.php +++ b/public/index.php @@ -68,15 +68,57 @@ function getCategories(): array { /** * Get the thumbnail image uri for the given category. */ -function getCategoryThumbnail(string $category): string { - $categoryImages = getCategoryImageFiles($category); - $firstImage = $categoryImages[0] ?? ''; - if (empty($firstImage)) { - return ''; +function generateImageThumbnail(string $category, string $image): void { + $imagePath = buildPath(IMAGES_DIR, $category, $image); + $thumbPath = buildPath(THUMBS_DIR, $category, $image); + + if (file_exists($thumbPath)) { + return; } - generateImageThumbnail($category, $firstImage); - return "thumbs/{$category}/{$firstImage}"; + if (!file_exists($imagePath)) { + error("Could not find image at {$imagePath}"); + } + + $thumbDir = dirname($thumbPath); + if (!file_exists($thumbDir)) { + mkdir($thumbDir, 0777, true); + } + + $imageExtension = strtolower(pathinfo($imagePath, PATHINFO_EXTENSION)); + + switch ($imageExtension) { + case 'webp': + $originalImage = imagecreatefromwebp($imagePath); + break; + case 'jpg': + case 'jpeg': + $originalImage = imagecreatefromjpeg($imagePath); + break; + case 'png': + $originalImage = imagecreatefrompng($imagePath); + break; + default: + error("Unsupported image format: {$imageExtension}"); + } + + $thumbImage = imagescale($originalImage, 1200); + + switch ($imageExtension) { + case 'webp': + imagewebp($thumbImage, $thumbPath, 50); + break; + case 'jpg': + case 'jpeg': + imagejpeg($thumbImage, $thumbPath, 50); + break; + case 'png': + imagepng($thumbImage, $thumbPath, 6); // Compression level for PNG: 0-9 + break; + } + + imagedestroy($originalImage); + imagedestroy($thumbImage); } /** @@ -133,7 +175,13 @@ function categoryExists(string $category): bool { * @return string[] */ function getCategoryImageFiles(string $category): array { - $images = glob(buildPath(IMAGES_DIR, $category, '*.webp')); + $extensions = ['webp', 'jpg', 'jpeg', 'png']; + $images = []; + + foreach ($extensions as $extension) { + $images = array_merge($images, glob(buildPath(IMAGES_DIR, $category, "*.{$extension}"))); + } + return array_map(fn(string $dir) => basename($dir), $images); } @@ -231,4 +279,5 @@ class Image { public string $uri, public string $thumb, ) {} -} \ No newline at end of file +} +?> \ No newline at end of file