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>
This commit is contained in:
parent
49e2700399
commit
31d8143500
7 changed files with 188 additions and 29 deletions
|
|
@ -15,6 +15,10 @@ export default function DatabaseSettings() {
|
|||
const [schemaMigrating, setSchemaMigrating] = useState(false);
|
||||
const [schemaActions, setSchemaActions] = useState(null);
|
||||
|
||||
const [compressBusy, setCompressBusy] = useState(false);
|
||||
const [compressResult, setCompressResult] = useState(null);
|
||||
const [compressError, setCompressError] = useState('');
|
||||
|
||||
const loadDbConfig = () => {
|
||||
setLoading(true);
|
||||
api.get('/settings/database').then((res) => {
|
||||
|
|
@ -50,6 +54,20 @@ export default function DatabaseSettings() {
|
|||
}
|
||||
};
|
||||
|
||||
const handleCompressUploads = async () => {
|
||||
setCompressBusy(true);
|
||||
setCompressError('');
|
||||
setCompressResult(null);
|
||||
try {
|
||||
const result = await api.post('/settings/compress-uploads', {});
|
||||
setCompressResult(result);
|
||||
} catch (err) {
|
||||
setCompressError(err.message);
|
||||
} finally {
|
||||
setCompressBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async (e) => {
|
||||
e.preventDefault();
|
||||
setSaveBusy(true);
|
||||
|
|
@ -213,6 +231,30 @@ export default function DatabaseSettings() {
|
|||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border border-neutral-200 bg-white p-6 dark:border-neutral-800 dark:bg-neutral-900">
|
||||
<h2 className="mb-1 font-semibold text-neutral-900 dark:text-white">Bilder optimieren</h2>
|
||||
<p className="mb-4 text-sm text-neutral-500 dark:text-neutral-400">
|
||||
Neu hochgeladene Bilder werden seit Kurzem automatisch verkleinert und komprimiert.
|
||||
Dieser Button holt das für alle bereits vorhandenen Bilder nach – nützlich, wenn die
|
||||
Seite durch zu hoch aufgelöste Fotos spürbar langsam lädt.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleCompressUploads}
|
||||
disabled={compressBusy}
|
||||
className="rounded-md bg-brand-500 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-600 disabled:opacity-50"
|
||||
>
|
||||
{compressBusy ? 'Komprimiert…' : 'Bestehende Bilder optimieren'}
|
||||
</button>
|
||||
{compressError && <p className="mt-3 text-sm text-red-600">{compressError}</p>}
|
||||
{compressResult && (
|
||||
<p className="mt-3 text-sm text-green-600 dark:text-green-400">
|
||||
{compressResult.processed} Bild(er) verkleinert: {(compressResult.before_bytes / 1024 / 1024).toFixed(1)} MB
|
||||
{' → '}
|
||||
{(compressResult.after_bytes / 1024 / 1024).toFixed(1)} MB.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -211,6 +211,8 @@ $router->post('/settings/reset-all', $perm('settings.manage', fn($p) => Settings
|
|||
$router->get('/settings/schema-check', $perm('settings.manage', fn($p) => SchemaController::check()));
|
||||
$router->post('/settings/schema-migrate', $perm('settings.manage', fn($p) => SchemaController::migrate()));
|
||||
|
||||
$router->post('/settings/compress-uploads', $perm('settings.manage', fn($p) => SettingsController::compressUploads()));
|
||||
|
||||
// Git-Auto-Update: eigene, engere Berechtigung (ueberschreibt Live-Code) statt des
|
||||
// breiteren settings.manage - siehe Kommentar bei Permissions::CATALOG['system.update'].
|
||||
$router->get('/settings/update-status', $perm('system.update', fn($p) => UpdateController::status()));
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ namespace App\Controllers;
|
|||
use App\Config\Database;
|
||||
use App\Support\Http;
|
||||
use App\Support\Slug;
|
||||
use App\Support\Uploads;
|
||||
use PDO;
|
||||
|
||||
class SettingsController
|
||||
|
|
@ -332,6 +333,40 @@ class SettingsController
|
|||
Http::send(['ok' => true, 'photos' => $photoCount]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Komprimiert nachtraeglich alle bereits vorhandenen Dateien in hifi/api/uploads/ (neue
|
||||
* Uploads werden seitdem schon direkt beim Hochladen komprimiert, siehe
|
||||
* UploadController::store()) - fuer Fotos, die schon vor dieser Änderung hochgeladen
|
||||
* wurden und die Seite dadurch spuerbar verlangsamen.
|
||||
*/
|
||||
public static function compressUploads(): void
|
||||
{
|
||||
$dir = __DIR__ . '/../../uploads/';
|
||||
$files = glob($dir . '*') ?: [];
|
||||
|
||||
$processed = 0;
|
||||
$beforeTotal = 0;
|
||||
$afterTotal = 0;
|
||||
foreach ($files as $file) {
|
||||
if (!is_file($file)) {
|
||||
continue;
|
||||
}
|
||||
$result = Uploads::compressImage($file);
|
||||
if ($result['changed']) {
|
||||
$processed++;
|
||||
$beforeTotal += $result['before'];
|
||||
$afterTotal += $result['after'];
|
||||
}
|
||||
}
|
||||
|
||||
Http::send([
|
||||
'ok' => true,
|
||||
'processed' => $processed,
|
||||
'before_bytes' => $beforeTotal,
|
||||
'after_bytes' => $afterTotal,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Löscht Marken (Foreign-Key-Kaskade räumt Modelle, Pakete, Produkte & Upgrades automatisch mit auf). */
|
||||
public static function resetCatalog(): void
|
||||
{
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
namespace App\Controllers;
|
||||
|
||||
use App\Support\Http;
|
||||
use App\Support\Uploads;
|
||||
|
||||
class UploadController
|
||||
{
|
||||
|
|
@ -40,6 +41,11 @@ class UploadController
|
|||
Http::error('Datei konnte nicht gespeichert werden', 500);
|
||||
}
|
||||
|
||||
// Verkleinert/komprimiert direkt beim Hochladen - vermeidet, dass ein zu grosses/zu
|
||||
// hochaufgeloestes Foto die Seite spuerbar verlangsamt, ohne dass sich am
|
||||
// gespeicherten Pfad/Format etwas aendert.
|
||||
Uploads::compressImage($destination);
|
||||
|
||||
$config = require __DIR__ . '/../../config/config.php';
|
||||
$prefix = rtrim($config['app']['base_path'], '/') . '/api/uploads/';
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,14 @@ 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)
|
||||
|
|
@ -44,4 +52,70 @@ class Uploads
|
|||
@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];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -43,7 +43,7 @@
|
|||
"sameAs": ["https://www.youtube.com/@hifiplanet2812"]
|
||||
}
|
||||
</script>
|
||||
<script type="module" crossorigin src="/assets/index-D9Qjl9YL.js"></script>
|
||||
<script type="module" crossorigin src="/assets/index-Cx42TygC.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/assets/lucide-icons-Cg2IxtAO.js">
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-Dcmvz3nM.css">
|
||||
</head>
|
||||
|
|
|
|||
Loading…
Reference in a new issue