0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel7でパッケージ「Intervention Image」を使って画像を加工する

Last updated at Posted at 2021-02-24

【開発環境】

Windows 10 HOME

Laravel Framework 7.25.0
PHP 7.4.7
Intervention Image 2.5

【目次】

  項目     
- はじめに
- 使い方
- インストールが上手くいかなかった時は
- 最後に

はじめに

Laravel7でパッケージ「Intervention Image」を使って画像を加工みてみた。

使い方

パッケージ「Intervention Image」をインストール。
対象のプロジェクト下でLaravelなので以下のようにcomposerで簡単にインストールできる。

composer require intervention/image

パッケージのダウンロード後に、サービスプロバイダの設定「config/app.php」に追加してLaravelに追記する。

	'providers' => [
、、、
		Intervention\Image\ImageServiceProvider::class,
	],
、、、
	'aliases' => [
、、、
		'InterventionImage' => Intervention\Image\Facades\Image::class,
	],

設定のキャッシュをクリアして設定はこれで終了。

php artisan config:clear

Laravelのコントローラでは
こんな感じで処理。


		$this->validate($request, [
			'file'=> [
				//必須
				'required',
				//アップロードされたファイル
				'file',
				//画像ファイル
				'image',
				//MIMEタイプを指定
				'mimes:jpeg,png',
			]
		]);

		if ($request->file('file')->isValid([])) {
				
			//ファイルアップロード処理
			$file = $request->file('file');
			//$name = $file->getClientOriginalName(); //元のファイル名のまま
			$name = Str::random(40).'.'.$file->getClientOriginalExtension(); //ランダムで40文字
			// 画像を横幅300px・縦幅アスペクト比維持の自動サイズへリサイズして保存先へ格納
			$tmpPath = public_path('storage/') . $name;
			$image = Image::make($file)
			->resize(200, null, function ($constraint) {
			$constraint->aspectRatio();
			})
			->save($tmpPath);


インストールが上手くいかなかった時は

こんなエラーが出たら、
メモリオーバーするしてるよっていうエラーです。

PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate xxxxxxxxxx bytes) in Unknown on line 0

解決策を検索すると「swapメモリの割当を増やしてから実行」という方法が出てくるが、設定などを変更せずに手っ取り早く済ませたい時はこれ。

COMPOSER_MEMORY_LIMIT=-1 composer  require intervention/image

この辺を参考

composer updateでmemoryが足りない場合の対応方法 その2

composer update でメモリオーバーする場合の対策

最後に

画像の処理は結構厄介なので
こういうツールがあるのはありがたいので
積極的に使っていきたいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?