How to convert image to Base 64 Data URI in PHP

One of the most important thing you can do to improve the load time of your website is reducing HTTP requests of your website. The more number of HTTP requests, more time your website will take in loading. This is why it is recommended to combine JS and CSS files into one file. You can also embed image direct in the page so that it does not request for a separate file. You can do this by converting an image into base64 data URI.
Base 64 Data URI allows you to convert an image into data string and hence you can embedded this data string directly into the browser. It will not hit another HTTP request for the image and help in reducing number of requests to make your website faster.
You can see the demonstration of the tool to convert image into Base 64 Data URI. If you also want to do something like this in PHP, follow the code below.
You only need to fetch the content of the image and then convert the data in Base 64.
$image = 'image.jpg'; $extension = 'jpg' $type = pathinfo($image, PATHINFO_EXTENSION); $data = file_get_contents($image); $dataUri = 'data:image/' . $extension . ';base64,' . base64_encode($data);
You can use the sample code added above in your existing code. I am not going to explain the full image upload system.
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.