0

I want to encode images in base64 for better solution to SEO proposes, I am fix some issues in audit and it say to use new image formats then load images as default like <img src='path/to/image.jpg'/> so on my research I found that base64 encoded images solve this warning in audit.

  • 1
    Using a base64 encoded image src might make the warning go away, but you haven't actually solved the problem. It's still a JPG. – Jacob Peattie Jul 1 at 8:31
0

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__."/".$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="<?php echo imageEncode("img/logo.jpeg");?>"/>

another path level: <img src="<?php echo imageEncodePath(__DIR__."/images/slider.png");?>"/>

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.