How to Convert Image File to Base64 String in Laravel

Sovary September 17, 2022 669
1 minute read

Hi Dev,

In this article we are going to discuss about Laravel how to convert image file to base64 string format. You will see how to convert image file to base64 format. Then we will look at example how convert the file to base 64 with Laravel. The below will give you simple exmple to turn image into base64 Laravel, and please look at a few steps to show example of convert image to base64 php laravel.

In some case you don't want to link you image path in html element, you may convert image to base64 string in laravel application. We will give two different ways, for first example we will place the image path and convert to base64 directly then second example we will convert image file object and convert to base64 string format.

How to Convert Image File to Base64 String

  • Example 1 - Convert Image Path to Base64
  • Example 2 - Convert Image File Object to Base64

Example 1 - Convert Image Path to Base64

Create File app -> Http -> Controllers -> FileController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class FileController extends Controller
{

    public function index()
    {
        $imagePath = public_path("images/test.jpg");
        $image = "data:image/jpeg;base64,".base64_encode(file_get_contents($imagePath));
  
        dd($image);
    }
}

Output #1

data:image/jpeg;base64,/9j/4RiDRXhpZgAATU0AKgA...

Example 2 - Convert Image File Object to Base64

Create File app -> Http -> Controllers -> FileController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class FileController extends Controller
{

    public function index(Request $request)
    {
        $request->validate([
            'file' => 'required',
        ]);
        $image = "data:image/png;base64,".base64_encode(file_get_contents($request->file('file')->path()));
        dd($image);
    }
}

Output #2

data:image/png;base64,/9j/4RiDRXhpZgAATU0AKgA...

You may also like..

 

Laravel  PHP 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him