HifiPlanet-Website/hifi/api/src/Support/Uploads.php
Maaxxs 31d8143500 Compress uploaded images automatically to speed up page loads
Photos were being served exactly as uploaded, at whatever resolution and
quality the source file had - a multi-megabyte camera/phone photo shown
in a small tile still cost the visitor its full download weight.

Uploads::compressImage() (new) downscales an image to a 1920px long edge
if it's larger, and re-encodes it (JPEG quality 82, WEBP quality 82, PNG
best compression) in place - same path, same format, just a lighter
file. UploadController::store() now runs every new upload through it
automatically, so this fixes itself going forward with no admin action
needed.

For images already sitting in uploads/ from before this change,
SettingsController::compressUploads() (new endpoint, Einstellungen ->
Datenbank -> "Bilder optimieren") re-processes every existing file in
place and reports how much space was reclaimed - covers exactly the
photos causing today's slow loads.

Uses GD (near-universally available on shared hosting, unlike Imagick)
and does nothing instead of erroring if the extension or an unrecognized
file type is encountered, so an environment without GD just keeps
today's behavior rather than breaking uploads.

Verified locally (GD wasn't enabled in this XAMPP install, enabled it to
test - same php.ini already had zip enabled for the git-updater feature):
a synthetic 3000x2000 JPEG dropped from ~1.86MB to ~279KB and a test PNG's
alpha transparency survived resizing intact. Did not run the bulk
compressor against this repo's own uploads/ folder, since ~200 of those
files are git-tracked seed/demo images, not disposable local test data.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 03:23:31 +02:00

121 lines
4.6 KiB
PHP

<?php
namespace App\Support;
/**
* Kuemmert sich darum, dass ein durch ImageUploadField ersetztes oder entferntes Bild
* nicht als verwaiste Datei in hifi/api/uploads/ liegen bleibt. Bisher loeschte kein
* einziger Controller je eine physische Datei - jedes Ersetzen/Entfernen eines Bildes
* hat die alte Datei einfach auf der Platte gelassen.
*/
class Uploads
{
private const DIR = __DIR__ . '/../../uploads/';
// Groessere Fotos werden auf diese laengste Seite herunterskaliert - reicht fuer alle
// aktuellen Verwendungen (Kacheln, Hero-Bild, Galerie), spart aber bei einem direkt von
// der Kamera/dem Handy hochgeladenen Foto oft mehrere MB und damit Ladezeit.
private const MAX_DIMENSION = 1920;
private const JPEG_QUALITY = 82;
private const WEBP_QUALITY = 82;
private const PNG_COMPRESSION = 6;
/**
* Loescht $oldPath von der Platte, aber nur wenn es sich tatsaechlich von $newPath
* unterscheidet (sonst wuerde ein unveraendert gespeichertes Bild sich selbst loeschen)
* und der Dateiname (ueber basename() aufgeloest, kein Path-Traversal moeglich)
* wirklich innerhalb von hifi/api/uploads/ liegt.
*/
public static function deleteIfOrphaned(?string $oldPath, ?string $newPath): void
{
$oldPath = trim((string) $oldPath);
$newPath = trim((string) $newPath);
if ($oldPath === '' || $oldPath === $newPath) {
return;
}
$filename = basename($oldPath);
if ($filename === '' || $filename === '.' || $filename === '..') {
return;
}
$fullPath = self::DIR . $filename;
$resolved = realpath($fullPath);
$uploadsDir = realpath(self::DIR);
if ($resolved === false || $uploadsDir === false || !str_starts_with($resolved, $uploadsDir)) {
return;
}
if (is_file($resolved)) {
@unlink($resolved);
}
}
/**
* Skaliert ein Bild auf die konfigurierte Maximalgroesse herunter und komprimiert es neu,
* direkt an derselben Datei (Format/Dateiname bleiben gleich - nur der Inhalt wird
* ersetzt). Tut absichtlich nichts, statt einen Fehler zu werfen, wenn die
* PHP-Erweiterung "gd" fehlt oder die Datei kein von GD lesbares Bild ist - betrifft dann
* nur Umgebungen/Dateien, auf die diese Optimierung nicht anwendbar ist.
*
* @return array{changed: bool, before: int, after: int}
*/
public static function compressImage(string $absolutePath): array
{
$before = is_file($absolutePath) ? (@filesize($absolutePath) ?: 0) : 0;
$noop = ['changed' => false, 'before' => $before, 'after' => $before];
if (!extension_loaded('gd') || !is_file($absolutePath)) {
return $noop;
}
$info = @getimagesize($absolutePath);
if (!$info) {
return $noop;
}
[$width, $height, $type] = $info;
$image = match ($type) {
IMAGETYPE_JPEG => @imagecreatefromjpeg($absolutePath),
IMAGETYPE_PNG => @imagecreatefrompng($absolutePath),
IMAGETYPE_WEBP => function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($absolutePath) : false,
default => false,
};
if (!$image) {
return $noop;
}
// Nur verkleinern, nie vergroessern.
$scale = min(1, self::MAX_DIMENSION / max($width, $height));
if ($scale < 1) {
$newWidth = max(1, (int) round($width * $scale));
$newHeight = max(1, (int) round($height * $scale));
$resized = imagecreatetruecolor($newWidth, $newHeight);
if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_WEBP) {
imagealphablending($resized, false);
imagesavealpha($resized, true);
}
imagecopyresampled($resized, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagedestroy($image);
$image = $resized;
}
$saved = match ($type) {
IMAGETYPE_JPEG => imagejpeg($image, $absolutePath, self::JPEG_QUALITY),
IMAGETYPE_PNG => imagepng($image, $absolutePath, self::PNG_COMPRESSION),
IMAGETYPE_WEBP => function_exists('imagewebp') ? imagewebp($image, $absolutePath, self::WEBP_QUALITY) : false,
default => false,
};
imagedestroy($image);
if (!$saved) {
return $noop;
}
clearstatcache(true, $absolutePath);
$after = @filesize($absolutePath) ?: $before;
return ['changed' => true, 'before' => $before, 'after' => $after];
}
}