Encode image to Base64 in PHP
PHP does not have a built-in function for encoding files, but we can do this using base64_encode and any function to read the whole file. Below I will show examples for encoding images, but you can adapt the code to your liking for any files.
The simplest example is how to encode an image to Base64 in PHP:
<?php
// Define local path or URL of our image
$img_file = '/files/images/1x1.gif';
// Load file contents into variable
$bin = file_get_contents($img_file);
// Encode contents to Base64
$b64 = base64_encode($bin);
// Show the Base64 value
echo $b64; //-> "R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs="
If you often need to encode the same files to Base64, consider to improve performance by caching the results as follows:
<?php
$img_file = '/files/images/1x1.gif';
$b64_file = "{$img_file}.b64";
if (is_file($b64_file)) {
$b64 = file_get_contents($b64_file);
} else {
$bin = file_get_contents($img_file);
$b64 = base64_encode($bin);
file_put_contents($b64_file, $b64);
}
echo $b64;
A ready-made function for displaying images on HTML pages:
<?php
/**
* Convert an image to Base64 for embedding in HTML
* @param string $img_file - Local path to the image
* @param string $alt - Alternative text description
* @param boolean $cache - Whether to cache the encoding result or not
* @param string $ext - Leave blank to determine the type of image by its extension
* @return boolean|string
*/
function base64_encode_html_image($img_file, $alt = null, $cache = false, $ext = null)
{
if (!is_file($img_file)) {
return false;
}
$b64_file = "{$img_file}.b64";
if ($cache && is_file($b64_file)) {
$b64 = file_get_contents($b64_file);
} else {
$bin = file_get_contents($img_file);
$b64 = base64_encode($bin);
if ($cache) {
file_put_contents($b64_file, $b64);
}
}
if (!$ext) {
$ext = pathinfo($img_file, PATHINFO_EXTENSION);
}
return "<img alt='{$alt}' src='data:image/{$ext};base64,{$b64}' />";
}
$img_file = '/files/images/1x1.gif';
$html = base64_encode_html_image($img_file, '1x1');
echo $html; //-> "<img alt='1x1' src='data:image/gif;base64,R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs=' />"
Regarding to the last example, please read about embedding Base64 images in HTML.
Comments (9)
I hope you enjoy this discussion. In any case, I ask you to join it.