人気のPHP WEBアプリケーションフレームワークLaravelのTipsを記録していきます

Laravel で intervention/image を使って画像変換する

● Laravel で intervention/image を使って画像変換する

(準備) ImageMagickがインストール済みかどうかを確認する

convert -version

Version: ImageMagick 6.7.8-9 2019-02-01 Q16 http://www.imagemagick.org のようにバージョンが表示されればOKです

(準備) intervention/image のインストール

composer require intervention/image

(準備) /config/image.php の自動生成

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"

(準備) /config/image.php の設定 (ドライバをimagickに変更 )

    // 'driver' => 'gd'
    'driver' => 'imagick'
“imagick” is much faster than “gd” , even 3 times more faster!

https://bit.ly/3gEtY9N

1. 画像の読み込み

パスから読み込み

$interv = \Image::make( storage_path('app/images/test.png') );

URLから読み込み

$interv = \Image::make( 'https://www.xxx.com/xxx/test.jpg' );

base64データから読み込み

$data = file_get_contents($path);
$data_url = 'data:image/png;base64,'. base64_encode($data);
$interv = \Image::make($data_url);

2. 画像フォーマットの変更

jpgフォーマットへ変換

$jpg = $interv->encode('jpg');

3. 画像を保存

$interv->save($save_path);

4. 画像を Amazon AWS S3 へ保存

S3へ保存するときは文字列変換をかませます

 $data = $interv->__toString();
 \Storage::disk($file_store_disk)->put("{$file_store_dir}/{$image_name}", $data);

● 画像サイズ、画像情報を取得する

$interv->width(); // 幅
$interv->height(); // 高さ
$interv->filesize(); // ファイルサイズ
$interv->mime(); // mimeタイプ
$interv->exif(); // exif情報

● 画像サイズを変更する

横幅 800px
縦幅 自動
でリサイズする

$interv->resize(800, null, function($constraint){
    $constraint->aspectRatio();
});

● 画像を最適化する

https://github.com/spatie/laravel-image-optimizer
https://ariteku.hatenablog.com/entry/2020/08/02/082201

No.1932
05/04 10:10

edit