With this midification, all images found in your /public directory and all recursive directories will be encoded to base64 on the fly.
- start by running the code
php artisan make:middleware EncodeImagePaths
to create a new middleware file.
-
add this code to the newly created middleware file.
namespace App\Http\Middleware;
use Closure;
class EncodeImagePaths
{
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response instanceof \Illuminate\Http\Response) {
$content = $response->getContent();
// Regex to find image paths more generally
$pattern = '/src="([^"]+\.(jpg|jpeg|png|gif))"/i';
$callback = function ($matches) {
$imagePath = public_path($matches[1]); // Get the absolute path of the image
if (file_exists($imagePath)) {
$type = pathinfo($imagePath, PATHINFO_EXTENSION);
$data = file_get_contents($imagePath);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return 'src="' . $base64 . '"';
} else {
return $matches[0]; // No change if file doesn't exist
}
};
// Replace content
$newContent = preg_replace_callback($pattern, $callback, $content);
$response->setContent($newContent);
}
return $response;
}
}
- Add this middleware to your kenel.php file
protected $middleware = [
// other middleware
\App\Http\Middleware\EncodeImagePaths::class,
];
- Done.
With this midification, all images found in your /public directory and all recursive directories will be encoded to base64 on the fly.
php artisan make:middleware EncodeImagePaths
to create a new middleware file.
add this code to the newly created middleware file.
namespace App\Http\Middleware;
use Closure;
class EncodeImagePaths
{
public function handle($request, Closure $next)
{
$response = $next($request);
}
protected $middleware = [
// other middleware
\App\Http\Middleware\EncodeImagePaths::class,
];