LoginSignup
2
2

More than 3 years have passed since last update.

InterventionImageで編集した画像ファイルをbase64変換してMySQLに保存する

Posted at

やりたいこと

InterventionImageで編集した画像ファイルをバイナリーに変換してMySQLに保存したい
もちろん画像ファイルは/public配下やS3などのファイルシステムに保存するのが定石なのは承知の上で、今回は手軽さを優先してDBに画像ファイル自体をtextカラムに保存する

環境


% sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.7
BuildVersion:   19H2

% docker version
Client: Docker Engine - Community
 Cloud integration: 1.0.1
 Version:           19.03.13
 API version:       1.40

# php -v
PHP 7.4.7 (cli) (built: Jun 11 2020 18:41:17) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Xdebug v2.9.6, Copyright (c) 2002-2020, by Derick Rethans

# php artisan -v     
Laravel Framework 7.26.1

# mysql --version
mysql  Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using  EditLine wrapper

Intervention Image とは

ImageMagikの上位互換?のモダンな画像編集パッケージ
リサイズ、トリミング、フィルターとなんでも手軽にできるっぽい
詳しくは公式doc参照

MySQLに画像バイナリを保存する

UserController
    public function update(Request $request, User $user)
    {
        // InterventionImageで加工&保存
        $file = $request->file('profile_img');
        $img = Image::make($file);
        $img->fit(400); //400px * 400px にトリム&リサイズ
        $bin = base64_encode($img->encode('png'));

        $user->profile_img = $bin;
        $user->save();
        return redirect()->route('user.index');
    }

ポイントは$bin = base64_encode($img->encode('png'));の1行。
base64_encodeする前に一度InterventionImageインスタンスをエンコードしている。
この処理がないとbase64_encodeしても空文字が生成される。なぜかはよくわからない。

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