Open In App

How to convert an image to base64 encoding in PHP?

The base64_encode() function is an inbuilt function in PHP which is used to convert any data to base64 encoding. In order to convert an image into base64 encoding firstly need to get the contents of file. This can be done with the help of file_get_contents() function of PHP. Then pass this raw data to base64_encode() function to encode.

Required Function:



Input Image:

Program:






<?php 
  
// Get the image and convert into string
$img = file_get_contents(
  
// Encode the image string data into base64
$data = base64_encode($img);
  
// Display the output
echo $data;
?>

Output:

iVBORw0KGgoAAAANSUhEUgAAApsAAAC4CAYAAACsNSfVAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJ
cEhZcwAADsQAAA7EAZUrDhsAAAAZdEVYdFNvZnR3YXJdhfdsglgklAEFkb2JlIEltYWdlUmVhZHlxyWqwrwtwefd
...
TeUsalQKBQKhUKhsBvK2FQoFAqFQqFQ2A1lbCoUCoVCoVAo7IYyNhUKhUKhUCgUdkMZmwqFQKBQKO0H0fxpZ1bfc

Reference:

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

Article Tags :