Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encode all your image directories to base64 before passing them to a browser #115

Open
ffeel31 opened this issue Apr 23, 2024 · 0 comments

Comments

@ffeel31
Copy link

ffeel31 commented Apr 23, 2024

With this midification, all images found in your /public directory and all recursive directories will be encoded to base64 on the fly.

  1. start by running the code
    php artisan make:middleware EncodeImagePaths

to create a new middleware file.

  1. 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;
}

}

  1. Add this middleware to your kenel.php file

protected $middleware = [
// other middleware
\App\Http\Middleware\EncodeImagePaths::class,
];

  1. Done.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant