How to Convert Image to Base64 in Laravel?

Hello dev, Today we are going to learn How to Convert Image to Base64 in Laravel. This tutorial will cover on how you can covert any image to Base64 in laravel 9 application.

We will look at an example of convert images to base64 laravel. This post will give you a simple example of convert images into base64 laravel. So, let’s follow a few steps to create an example of convert images to base64 php laravel.

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

Sometimes, we require to convert images 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.

Also Read: How to Get Browser Name and Version in Laravel 9?

Examples for How to Convert Image to Base64 in Laravel?

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....

Also Read: Laravel 9 Custom Login and Registration Example

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....

Conclusion:

Today, We had learn How to Convert Image to Base64 in Laravel?. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: How to Integrating AdminLTE 3 in Laravel 9?

2 Comments

Leave a Reply