LoginSignup
0
1

More than 1 year has passed since last update.

【メモ】intervention/imageを使って画像のリサイズとストレージへの保存

Last updated at Posted at 2021-04-11

バージョン

  • PHP7.3
  • Laravel7.30

ライブラリのインストール

$ composer require intervention/image

実装

プロバイダ登録

config/app.php

'providers' => [
  // 中略
  App\Providers\RouteServiceProvider::class,
  Illuminate\View\ViewServiceProvider::class,  // 追加
],

'aliases' => [
  'InterventionImage' => Intervention\Image\Facades\Image::class,
]
/var/www/laravel
$ php artisan config:cache

保存

横幅 500px で保存してみる


public function store(Request $request)
{
  if (Storage::missing('public/resized')) {
    Storage::makeDirectory('public/resized');
  }

  $file = $request->file('test_image');
  $response = $this->putResizedFile($file, storage_path('app/public/resized/test_image.' . $file->extension()), 500);

  return response($response, 200);
}

/**
  * @param $fileData = リソース
  * @param string $tempPath = 保存先
  * @param int $width サムネイルのサイズ
  * @return \Intervention\Image\Image
  */
protected function putResizedFile($fileData, $tempPath, int $width)
{
  return \InterventionImage::make($fileData)->resize($width, null, function ($constraint) {
    $constraint->aspectRatio();
  })->save($tempPath);
}

削除

Storage ファサードを使う

Storage::delete('public/resized/test_image.png');

注意点

storage/app/public直下にresizedディレクトリがない場合、勝手にディレクトリを作るようなことはなくエラーが出るため**Storage::missing()**でチェックしている。

storage/laravel.log
"Can't write image data to path (/var/www/laravel/storage/app/public/resized/test_image.png)"

この点、Storage::put('public/resized/test_image.png')の場合は勝手に作ってくれることと比較。

0
1
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
0
1