times-kzm

life log

Laravelで画像をまとめてリサイズ&最適化

ライブラリ

フォルダを渡して、まとめて画像をリサイズするコードを書いてみました。

composer require spatie/laravel-image-optimizer
composer require intervention/image
// config/app.php
    'providers' => [
        .....
        Intervention\Image\ImageServiceProvider::class,
    ]

作成するコマンド

php artisan command:image-resize {元画像フォルダ} {出力先フォルダ}

コード

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Intervention\Image\Facades\Image;
use Spatie\LaravelImageOptimizer\Facades\ImageOptimizer;

class ImageResize extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:image-resize {src} {dst}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Resize mages';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $src = $this->argument('src');
        $dst = $this->argument('dst');

        foreach (glob("$src/*.jpg") as $file) {
            if (is_file($file)) {
                echo "resize: $file", PHP_EOL;

                $image = Image::make($file)->resize(498, null, function ($constraint) {
                    $constraint->aspectRatio();
                });
                $basename = pathinfo($file)['basename'];
                $file_dst = "{$dst}/$basename";
                $image->save($file_dst);

                ImageOptimizer::optimize($file_dst);
            }
        }
    }
}
// app/Console/Kernel.php
    protected $commands = [
        //
        \App\Console\Commands\ImageResize::class,
    ];