How to Convert Image File to Base64 String in Laravel

Sovary September 17, 2022 990
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him