Convert an image to base64 encoded string in PHP
Today we’ll show you how to convert an image to base64 encoded string in PHP. In this article we will create a sample demo for you to get base64 string from image data.
php base64 encoded image from url, php decode base64 image and display, php base64 encode uploaded image, php base64 encode image, convert image to base64 php online, convert base64 to image codeigniter, base64 encode and decode in php, converting image to string in php, use pathinfo, file_get_contents & base64_encode functions to convert image data to base64 string.
Checkout more articles on PHP
- How to use session in PHP
- Sorting Arrays in PHP
- Convert CSV to JSON in PHP
- Get keys from an associative array in PHP
Example to convert an image to base64 encoded string
In this example we will use a couple of inbuilt PHP’s functions like pathinfo(), file_get_contents() and base64_encode() to convert image data to base64 image string and display it in image tag.
index.php
<?php
// path of image
$img_path = './images/test.jpg';
// get the extension of the image to generate base64 string
$type = pathinfo($img_path, PATHINFO_EXTENSION);
// get the file data
$img_data = file_get_contents($img_path);
// get base64 encoded code of the image
$base64_code = base64_encode($img_data);
// create base64 string of image
$base64_str = 'data:image/' . $type . ';base64,' . $base64_code;
?>
<h3>Convert an image to base64 encoded string - <a href="https://www.cluemediator.com" target="_blank">Clue Mediator</a></h3>
<img src="<?= $base64_str; ?>" width="300" style="border:1px solid #ddd;"/>
If you check the value of the `$base64_str` variable then it's look like below.
data:image/jpg;base64,iVBORw0K...rkJggg==
Let’s try to understand code line by line.
- Define the path of the image to convert it to base64 encoded string.
- Use pathinfo() function to get the extension of the image.
- Now in the next step we have to get the file data using file_get_contents().
- It’s time to use base64_encode() function to get base64 encoded code using file contents.
- At last we are going to create a base64 string based on the generated data and use it to display the image in an image tag.
Run code and check the output in the browser.
Output - Convert an image to base64 encoded string in PHP - Clue Mediator
In the upcoming article, we will see how to get an image from base64 code and save it in the given path of the directory.
Thank you for reading. Happy Coding!