Hi there! If you’re working on a Laravel application and need advanced image processing capabilities, Python’s libraries like OpenCV and PIL (Pillow) can be your best friend. In this guide, I’ll show you how to seamlessly integrate Python with Laravel for image processing.
We'll set up communication between Laravel and Python scripts using HTTP requests, process images dynamically, and return the processed files back to Laravel.
Integrating Python Image Processing with Laravel
Before integrating Python with Laravel, we need to install Python and the necessary libraries for image processing.
python --version
Install the required libraries using pip:
pip install opencv-python flask pillow
To enable Laravel to communicate with Python, we’ll create a Flask server to handle image processing requests.
image_processor.py
from flask import Flask, request, jsonify, send_file
from PIL import Image, ImageFilter
import cv2
import numpy as np
import io
app = Flask(__name__)
@app.route('/process-image', methods=['POST'])
def process_image():
try:
# Retrieve the image from the POST request
file = request.files['image']
operation = request.form.get('operation', 'blur')
# Open the image using PIL
img = Image.open(file)
# Perform operations based on the requested type
if operation == 'blur':
img = img.filter(ImageFilter.BLUR)
elif operation == 'grayscale':
img = img.convert('L')
# Save processed image to a BytesIO stream
img_io = io.BytesIO()
img.save(img_io, 'JPEG')
img_io.seek(0)
return send_file(img_io, mimetype='image/jpeg')
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
Save this file and run it:
python image_processor.py
Laravel’s HTTP client makes it easy to send requests to the Flask server. If you’re using Laravel 9 or later, the HTTP client is already available.
Create a controller to send images to the Python server and retrieve the processed image.
php artisan make:controller ImageProcessingController
ImageProcessingController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
class ImageProcessingController extends Controller
{
public function processImage(Request $request)
{
// Validate input
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
'operation' => 'required|string',
]);
// Send the image and operation to the Python server
$response = Http::attach(
'image',
$request->file('image')->getContent(),
$request->file('image')->getClientOriginalName()
)->post('http://127.0.0.1:5000/process-image', [
'operation' => $request->input('operation'),
]);
if ($response->failed()) {
return response()->json(['error' => 'Image processing failed'], 500);
}
// Save the processed image locally
$processedImage = $response->body();
$filename = 'processed_image.jpg';
Storage::put("public/images/$filename", $processedImage);
return response()->json(['message' => 'Image processed successfully', 'file' => asset("storage/images/$filename")]);
}
}
Add a route in web.php to handle image processing requests.
use App\Http\Controllers\ImageProcessingController;
Route::post('/process-image', [ImageProcessingController::class, 'processImage']);
Create a form to upload an image and select an operation.
resources/views/process_image.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Processing</title>
</head>
<body>
<h1>Image Processing with Laravel and Python</h1>
<form action="/process-image" method="POST" enctype="multipart/form-data">
@csrf
<label for="image">Upload Image:</label>
<input type="file" name="image" id="image" required>
<br>
<label for="operation">Select Operation:</label>
<select name="operation" id="operation">
<option value="blur">Blur</option>
<option value="grayscale">Grayscale</option>
</select>
<br>
<button type="submit">Process Image</button>
</form>
</body>
</html>
Start the Laravel development server:
php artisan serve
You might also like: