Laravel + Guzzel でフォームから画像をアップロードしてPythonの画像処理APIを叩く
1. はじめに
下記の記事の応用として、フォームから画像をアップロードできるようにし、 Pythonの画像処理APIを叩く記事です。
2. コントローラーの作成
下記コマンドでコントローラーを新規作成します。
php artisan make:controller UploadController
コントローラーの中身は下記のコードにします。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use GuzzleHttp\Client; class UploadController extends Controller { public function index(){ return view('upload'); } public function upload(Request $request) { // 画像を保存 $file_name = $request->file('image')->store('public'); $file_name = explode('/', $file_name, )[1]; var_dump($file_name); // APIを叩く準備 $client = new Client([ 'headers' => [ 'Content-Type' => 'application/json' ] ]); // base64で画像を読み込んでエンコード $input_data = base64_encode(file_get_contents('storage/' . $file_name)); $resp = $client->post('http://localhost:5000/image', ['body' => json_encode( [ [ 'id' => 1, 'Image' => $input_data ] ] )] ); $resp_json = json_decode($resp->getBody(),true); #var_dump($resp_json); $id = $resp_json[0]['id']; $result = $resp_json[0]['result']; return view('ai-image', [ 'id' => $id, 'result' => $result ]); } }
3. ルーティングの設定
ルーティングの設定をします。
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\UploadController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/upload', [UploadController::class, 'index']); Route::post('/upload', [UploadController::class, 'upload']);
4. viewファイルの設定
<!DOCTYPE html> <html> <body> <form method="POST" action="/upload" enctype="multipart/form-data"> @csrf <input type="file" name="image"> <button>アップロード</button> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AI Image Test</title> </head> <body> <h1>id: {{ $id }}</h1> <img src="data:image/png;base64,{{ $result }}" /> </body> </html>
upload.blade.php は、このような感じの表示になります。
5. 動作結果
Pythonのflaskサーバーを起動します。
python3 app.py
Laravelのサーバーを起動します。
php artisan serve --host=localhost --port=8000
http://localhost:8000/upload にアクセスし、 画像をアップロードした結果が以下です。 グレースケール化された画像がちゃんとPythonの画像処理APIを介してブラウザに表示されました!