Encode and Get the Base64 of an Image in PHP

By Faruque Ahamed Mollick

Here we are now going to learn how to encode and get the base64 code of an image in PHP. I hope, you will enjoy this tutorial.

Base64 represent binary data in an ASCII string format by translating it into a radix-64 representation. Using PHP, we can create the base64 of an image type file in an easy way. We can also do it for any types of file.

PHP has a function base64_encode() which can be used to create the base64 code of any image. In this function, we just have to pass the image content string. We can get the content of a file into the string using the file_get_contents() PHP function.

Now let’s see the code below:

<?php
$img_path = 'path/test.jpg';
$type = pathinfo($img_path, PATHINFO_EXTENSION);
$img_data = file_get_contents($img_path);
// Create base64 code of image.
$base64_code = base64_encode($img_data);
?>

In the above code, we have first read the contents of the image file into a string. From the image file content string, we can get the base64 encoded code.

Using the base64_encode PHP function, we can create the base64 code of our image file. In our code, we have used this function. We have just passed the variable where we have assigned the string content of our image file to the base64_encode() function. As a result, it returns the base64 code of the image.

Now, to check if the base64 is correct, we can show the image using HTML <img> tag. We will use the HTML img tag in the same procedural way, but in the src attribute, we will pass the base64 code. Below is the code to show the image from the base64 code:



<img src="data:image/png;base64,<?php echo $base64_code; ?>">

In the above HTML, we have passed the base 64 code in the <img> tag in the src attribute. First, we have declared it as base64 image data with “data:image/png;base64,” and right next put our base64 code.

If all works correctly, then we will be able to see the picture on the page.

I hope you can have understood this tutorial.

 

Leave a Reply

Your email address will not be published. Required fields are marked *