LoginSignup
3
2

More than 5 years have passed since last update.

Laravelでフォームから送信された画像を縦横比を維持したままリサイズする

Last updated at Posted at 2018-05-21

パッケージのインストール

$ composer require intervention/image

configの書き換え

Vimを使っていると、適当な位置にペーストして
Shift + v で行選択、:sort uで並び替えると便利

config/app.php
'providers' => [
    ...
    Intervention\Image\ImageServiceProvider::class,
    ...
];
...
'aliases' => [
    ...
    'Image' => Intervention\Image\Facades\Image::class,
    ...
];

storageとpublicフォルダをリンクする

$ php artisan storage:link

Controller

app/Http/Controllers/HogehogeController.php
class HogehogeController extends Controller
{
...
    public function store(Request $request)
    {
        // ファイルを保存&ファイルの保存先URLを取得
        $filepath  = $this->save_imagefile($request);

        $hogehoge = new Hogehoge;
        $hogehoge->fill($request->all());
        $hogehoge->filepath = $filepath;
        $hogehoge->save();

        $message = [
            'type'      => 'success'
            , 'text'    => '登録が完了しました'
        ];
        return redirect()->route('hogehoges.index')->with('message', $message);
    }

    /**
     * 写真を保存する
     *
     * @param $request
     * @return string 保存するファイル名
     */
    private function save_imagefile($request)
    {
        // ファイルがアップロードされていない場合、nullを返す
        if (is_null($request->file)) return null;

        $filepath  = '/storage/hogehoges/' . md5(date('YmdHis')) . '.' . $request->file->getClientOriginalExtension();

        // resize
        $exif = Image::make($request->file)->exif();
        if (is_null($exif)) return null;
        $width  = 400;
        // 横幅と比例してリサイズするための高さを計算する
        $height = $exif['COMPUTED']['Height'] / ($exif['COMPUTED']['Width'] / $width);
        Image::make($request->file)->resize($width, $height)
                                   ->save(public_path() . $filepath);

        return $filepath;
    }
...
}

参考サイト

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2