How to Convert Image to Base64 in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Convert JSON to Array in Laravel?
- How to use Carbon in Laravel Blade or Controller File?
- How to Call Controller Function in Blade Laravel?
- How to Override Auth Login Method in Laravel 8?
- How to use Google Recaptcha V3 in Laravel App?
- Laravel Convert PDF to Image Example
- How to add Default Value of Column in Laravel Migration?
- Laravel Carbon Convert String to Date Example
- Laravel Carbon Check If Date is Greater Than Other Date
- How to Convert Object to Array in Laravel?
- How to Get Last Inserted Id in Laravel?
- How to Get Query Log in Laravel Eloquent?