how to base64 encode images in wordpress template

in your file functions.php in your template put this funcitons

/**
* @param $path
* @return string
* @author https://github.com/ozzpy
*/
function imageEncode($path)
{
$path  = __DIR__."https://wordpress.stackexchange.com/".$path;
$image = file_get_contents($path);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$type  = $finfo->buffer($image);
return "data:".$type.";charset=utf-8;base64,".base64_encode($image);
}

/**
 * @param $path
 * @return string
 * @author https://github.com/ozzpy
 */
function imageEncodePath($path)
{
$image = file_get_contents($path);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$type  = $finfo->buffer($image);
return "data:".$type.";charset=utf-8;base64,".base64_encode($image);
}


/**
 * @param $path
 * @return string
 * @author https://github.com/ozzpy
 */
function imageEncodeURL($path)
{
$image = file_get_contents($path);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$type  = $finfo->buffer($image);
return "data:".$type.";charset=utf-8;base64,".base64_encode($image);
}

in your html files in your template use it like:

template level:
<img src="https://wordpress.stackexchange.com/questions/341827/<?php echo imageEncode("img/logo.jpeg");?>"/>

another path level:
<img src="https://wordpress.stackexchange.com/questions/341827/<?php echo imageEncodePath(__DIR__."/images/slider.png");?>"/>

outside url level:
<img src="https://wordpress.stackexchange.com/questions/341827/<?php echo imageEncodeURL("https://somedomain.com/img/image.jpeg");?>"/>

Leave a Comment