jonnybarnes.uk/app/Jobs/ProcessMedia.php
Jonny Barnes 4569abc351
Add command to reprocess existing media with correct aspect-ratio scaling
ProcessMedia was using resize(), which distorts images that aren't the
target aspect ratio; scale() preserves it. Existing medium/small
variants generated before this fix need regenerating, so add an
artisan command (with --dry-run) to do that, plus feature tests.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-02 20:00:30 +01:00

69 lines
2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Exceptions\DecoderException;
use Intervention\Image\ImageManager;
class ProcessMedia implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(
protected string $filename
) {}
/**
* Execute the job.
*/
public function handle(ImageManager $manager): void
{
// Load file
$file = Storage::disk('local')->get($this->filename);
// Open file
try {
$image = $manager->read($file);
} catch (DecoderException) {
// not an image; delete file and end job
Storage::disk('local')->delete($this->filename);
return;
}
// Save the file publicly
Storage::disk('public')->put($this->filename, $file);
// Create smaller versions if necessary
if ($image->width() > 1000) {
$filenameParts = explode('.', $this->filename);
$extension = array_pop($filenameParts);
// the following achieves this data flow
// foo.bar.png => ['foo', 'bar', 'png'] => ['foo', 'bar'] => foo.bar
$basename = trim(implode('.', $filenameParts), '.');
$medium = $image->scale(width: 1000);
Storage::disk('public')->put($basename.'-medium.'.$extension, (string) $medium->encode());
$small = $image->scale(width: 500);
Storage::disk('public')->put($basename.'-small.'.$extension, (string) $small->encode());
}
// Now we can delete the locally saved image
Storage::disk('local')->delete($this->filename);
}
}