How to Convert Image Base64 in PHP?

03-Apr-2023

.

Admin

How to Convert Image Base64 in PHP?

Hi Dev,

This tutorial will give you example of how to convert image base64 in php?. This article goes in detailed on php convert image to base64. I would like to show you convert image to base64 in php. you will learn php image to base64 code example. Follow bellow tutorial step of convert image to base64 example.

Here, I will give the following example of how to convert image base64 in php program, we will use The file_get_contents() reads a file into a string. The base64_encode() function use to encode the given data with base64 this function allows you to encode data in the MIME Base64.

Example: Convert image to base64


index.php

<?php

// Define a path for the image

$image = 'demo.jpeg';

// Check image type

$image_type = pathinfo($image, PATHINFO_EXTENSION);

// Read the image into a string

$image_path = file_get_contents($image);

// Encode the image

$base64_encode = 'data:image:/' . $image_type . ';base64,' . base64_encode($image_path);

// Return the first 50 characters of the

// base64 encoded string

echo substr($base64_encode, 0, 50);

?>

Output:

data:image:/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA

I hope it could help you...

#PHP