LoginSignup
1
3

More than 3 years have passed since last update.

LaravelでS3にアップする画像のリサイズ

Last updated at Posted at 2020-12-02

目的

AWSの経費削減の為に画像品質を保証する前提でS3にアップする画像の圧縮をして欲しいと言うデイレクターからの要望を実現

必要条件

[1] ライブラリであるGDのインストール

$ yum install php-gd

# GD ライブラリの情報を確認
php -r 'print_r(gd_info());'

[2] Intervention Imageのインストール

$ composer require intervention/image

あるいはcomposer.jsonファイルに下記を追加
"intervention/image": "^2.5",

Laravelの設定

app\config\app.phpファイルに下記を追加
[1] Intervention Imageのサービスプロバイダの追加

'providers' => [
        Intervention\Image\ImageServiceProvider::class,
],

[2] Intervention Imageのファサードの追加

'aliases' => [
        'Image' => Intervention\Image\Facades\Image::class,
],

Controller作成

namespace App\Http\Controllers\User;

use Intervention\Image\Facades\Image as Image;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class UploaderController extends Controller
{
    public function putImageTmp()
    {
        $file = request()->file('file');

        $image = Image::make($file);
        $image->resize(70, 50);

        $path = request()->file('file')
                ->store(config('const.file_tmp_dir'));

        return response()->success([
            'url' => Storage::url($path),
            'path' => $path,
        ]);
    }

高さのみ指定し横は同じ比率でリサイズしたい場合

        $image->resize(null, 50, function ($constraint) {
            $constraint->aspectRatio();
        });

ちょっとだけハマったところ

[1] ライブラリであるGDのインストールされていないと下記のエラーが発生

local.ERROR: Call to undefined function Intervention\Image\Gd\imagecreatefromjpeg() {"userId":11,"exception":"[object] (Error(code: 0): Call to undefined function Intervention\\Image\\Gd\\imagecreatefromjpeg() at /var/www/html/projdir/vendor/intervention/image/src/Intervention/Image/Gd/Decoder.php:38)

[2] GD ライブラリの情報を確認

$ php -r 'print_r(gd_info());'

Array
(
    [GD Version] => bundled (2.1.0 compatible)
    [FreeType Support] => 1
    [FreeType Linkage] => with freetype
    [GIF Read Support] => 1
    [GIF Create Support] => 1
    [JPEG Support] =>      ←「JPEG Support」が有効になっていない
    [PNG Support] => 1
    [WBMP Support] => 1
    [XPM Support] => 1
    [XBM Support] => 1
    [WebP Support] =>
    [BMP Support] => 1
    [JIS-mapped Japanese Font Support] =>
)

[3]ライブラリであるGDのインストール

$ yum install php-gd

GD ライブラリの情報を確認

$ php -r 'print_r(gd_info());'

下記のようにJPEG Support」が「1」有効になればOK

[GIF Create Support] => 1

画像リサイズ結果

リサイズ前
スクリーンショット 2020-12-02 17.01.40.png

リサイズ後
スクリーンショット 2020-12-02 17.01.34.png

 画像リサイズ以外色々遊べます

モザイク

$img->pixelate(50);

グレースケール

$img->greyscale();
1
3
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
1
3