How to Convert Image to Base64 in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hi Friends,

In this tute, we will discuss laravel convert image to base64. you can see how to convert image to base64 in laravel. We will look at an example of convert image to base64 laravel. This post will give you a simple example of convert image into base64 laravel. So, let's follow a few steps to create an example of convert image to base64 php laravel.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Sometimes, we require to convert image to base64 string in laravel application. In this example, I will give you two examples to convert image to base64 string. in the first example, we will take image path and convert it into base64 image. in the second example, we will take the file object and convert it into base64 string.

without any ado, let's see examples of code.

Example 1:

app/Http/Controllers/DemoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$imagePath = public_path("images/20220405140258.jpg");

$image = "data:image/png;base64,".base64_encode(file_get_contents($imagePath));

dd($image);

}

}

Output:

data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQE....

Example 2:

app/Http/Controllers/DemoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DemoController extends Controller

{

/**

* Show the application dashboard.

*

* @return \Illuminate\Http\Response

*/

public function store(Request $request)

{

$request->validate([

'file' => 'required',

]);

$image = "data:image/png;base64,".base64_encode(file_get_contents($request->file('file')->path()));

dd($image);

}

}

Output:

data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQE....

I hope it can help you...

Tags :
Shares