PHP – Convert Image to Base64 String

This post shows you how to convert an image to a base64 string in PHP. The image can be either a URL or an image file on disk. The purpose of this is that we often want to save the image into the database.

 

1. Implementation

base64image.php
<?php

function convertImageToBase64($imagePath)
{
    $image = file_get_contents($imagePath);
    $base64String = base64_encode($image);
    return $base64String;   
}

In the above code, we first use file_get_contents to get the content of the image and then use base64_encode to convert the image content to the base64 string.

 

2. Usage

The image can be a file on disk.

$image = 'D:/path/to/your-image.jpg';
$base64String = convertImageToBase64($image);

Or it can be a URL like this.

$image = 'https://www.google.com.vn/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png';
$base64String = convertImageToBase64($image);

 

3. Example

$image = 'https://www.gravatar.com/avatar';
$base64String = convertImageToBase64($image);
echo $base64String;

The above code example, we convert the image from gravatar site to base64 string.

Leave a Reply

avatar