Files
ladill-qr-plus/app/Support/Qr/UploadedImageOptimizer.php
isaaccladandClaude 9ead4573d6 qr: downscale uploaded images before storing them
Uploads were written to the qr disk byte-for-byte. A bookshop cover arrived as a
9000x6600 print-resolution JPEG — 18MB — and was then served in full to every
visitor of a public bio page. During a launch that one file accounted for roughly
1.6GB of 1.9GB of image traffic, and because these assets are proxied through the
app rather than served statically, PHP streamed every byte of it and held a worker
for the duration.

Nothing the QR/bio pages display needs more than a couple of thousand pixels, so
UploadedImageOptimizer caps the long edge at 2000px and re-encodes on the way in.
The incident file becomes ~350KB. Configurable via qr.image.*.

Deliberately conservative, because a broken upload is worse than a large one:

- Format is preserved. A PNG stays a PNG so transparency survives; converting to
  JPEG would put black boxes behind logos.
- GIF is excluded — GD would silently drop animation frames.
- SVG and any file GD cannot read is stored untouched.
- Small files are passed through rather than lossily re-encoded for no gain.
- Output is discarded if it came out larger than the original.
- Any failure logs and falls back to storing the original.

Applied to the seven image paths only. Books (PDF/EPUB) and documents keep the
plain store — the optimiser would have fallen through for them anyway, but routing
non-images through something called an image optimiser invites the wrong change
later.

This is the source-level counterpart to the nginx cache: caching stops the bytes
being regenerated, this stops them existing.

Tests: 6 new, including the real 9000x6600 shape, PNG alpha survival, format
preservation and non-image passthrough. Pre-existing suite failures unchanged at 8.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-25 12:23:08 +00:00

163 lines
5.6 KiB
PHP

<?php
namespace App\Support\Qr;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Throwable;
/**
* Downscales and re-encodes uploaded images before they are stored.
*
* Uploads were previously written to the qr disk byte-for-byte. A bookshop cover
* arrived as a 9000x6600 print-resolution JPEG — 18MB — and was then served, in
* full, to every visitor of a public bio page. One file accounted for roughly
* 1.6GB of 1.9GB of image traffic during a launch, and PHP streamed every byte of
* it because these assets are proxied through the app rather than served statically.
*
* Nothing displayed by the QR/bio pages needs more than a couple of thousand pixels,
* so capping the long edge and re-encoding removes the problem at the source rather
* than relying on someone remembering to resize before uploading.
*
* Deliberately conservative:
* - Format is preserved. A PNG stays a PNG so transparency survives; converting to
* JPEG would put black boxes behind logos.
* - Anything not a plain raster image (SVG, animated GIF, unreadable file) is stored
* untouched — better an oversized file than a corrupted or flattened one.
* - If optimisation fails for any reason the original is stored, because a failed
* upload is worse than a large one.
*/
class UploadedImageOptimizer
{
/**
* Optimise and store an upload on the given disk.
*
* @return bool true when the stored bytes were optimised, false when the
* original was stored unchanged
*/
public static function store(UploadedFile $file, string $path, string $disk = 'qr'): bool
{
$optimised = self::encode($file);
if ($optimised === null) {
$file->storeAs('', $path, $disk);
return false;
}
Storage::disk($disk)->put($path, $optimised);
return true;
}
/**
* Re-encoded image bytes, or null when the file should be stored as-is.
*/
public static function encode(UploadedFile $file): ?string
{
if (! extension_loaded('gd')) {
return null;
}
$maxDimension = (int) config('qr.image.max_dimension', 2000);
$quality = (int) config('qr.image.jpeg_quality', 82);
try {
$realPath = $file->getRealPath();
if ($realPath === false || ! is_readable($realPath)) {
return null;
}
$info = @getimagesize($realPath);
if ($info === false) {
return null; // Not a raster image GD understands (e.g. SVG).
}
[$width, $height, $type] = $info;
if (! in_array($type, [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP], true)) {
// GIF excluded on purpose: GD would drop animation frames.
return null;
}
// Already small enough and not a heavyweight file: leave it alone rather
// than lossily re-encoding something that costs nothing to serve.
$longEdge = max($width, $height);
if ($longEdge <= $maxDimension && $file->getSize() <= (int) config('qr.image.passthrough_bytes', 512000)) {
return null;
}
$source = match ($type) {
IMAGETYPE_JPEG => @imagecreatefromjpeg($realPath),
IMAGETYPE_PNG => @imagecreatefrompng($realPath),
IMAGETYPE_WEBP => @imagecreatefromwebp($realPath),
};
if (! $source) {
return null;
}
$target = self::resize($source, $width, $height, $maxDimension, $type);
ob_start();
$ok = match ($type) {
IMAGETYPE_JPEG => imagejpeg($target, null, $quality),
// PNG 6 is a size/CPU compromise; PNG re-encode is lossless.
IMAGETYPE_PNG => imagepng($target, null, 6),
IMAGETYPE_WEBP => imagewebp($target, null, $quality),
};
$bytes = (string) ob_get_clean();
imagedestroy($source);
if ($target !== $source) {
imagedestroy($target);
}
if (! $ok || $bytes === '') {
return null;
}
// Never make a file bigger than it started.
return strlen($bytes) < $file->getSize() ? $bytes : null;
} catch (Throwable $e) {
Log::warning('image optimisation failed, storing original', [
'file' => $file->getClientOriginalName(),
'error' => $e->getMessage(),
]);
return null;
}
}
/**
* @param \GdImage $source
* @return \GdImage
*/
private static function resize($source, int $width, int $height, int $maxDimension, int $type)
{
$longEdge = max($width, $height);
if ($longEdge <= $maxDimension) {
return $source;
}
$scale = $maxDimension / $longEdge;
$newWidth = max(1, (int) round($width * $scale));
$newHeight = max(1, (int) round($height * $scale));
$target = imagecreatetruecolor($newWidth, $newHeight);
if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_WEBP) {
// Keep alpha; without this transparent areas come back black.
imagealphablending($target, false);
imagesavealpha($target, true);
$transparent = imagecolorallocatealpha($target, 0, 0, 0, 127);
imagefilledrectangle($target, 0, 0, $newWidth, $newHeight, $transparent);
}
imagecopyresampled($target, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
return $target;
}
}