Search code examples
phpbase64

Find and convert all images to base64 from html


Find and convert all images to base64 from html

I'm working on a screenshot project using html2canvas. My business is constrained by images that can not be rendered, so that all images from the url can not be displayed.

But I tried to replace one of the image urls with a new image that has been converted to base64, and it works.

So here I have found the solution, just can not apply to my site. I need help to compile the code in order to finish my project.

Could there be any way to change this code:

<?php
echo '
<html>
<body>
<div><img src="/image1.jpg" /></div>
<p><img src="/image2.png" /></p>
</body>
</html>
'
?>

TO

<?php
echo '
<html>
<body>
<div><img src="base64,/9j/4AAQSkZJRgABAQAAAQABAA_blablabla..." /></div>
<p><img src="base64,/9h/4AAQSkZJRgABAQAAAQABAA_blablabla..." /></p>
</body>
</html>
'
?>

I've tried with this code FROM How to convert an image to base64 encoding?

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

But can not apply it to all image URLs.

UPDATE===

The main topic of this question is how to convert all images to base64

I assume how it works if using jQuery like this:

<script>
$(function(){
    $('img').each(function() {
        $(this).attr('src', 'BASE64 GENERATED');
    });
});
</script>

Solution

  • the best practice to follow is the DOMDocument , here's an example of how to do that .

    $html = '<html>....</html>';
    $dom = new DOMDocument();
    $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    $images = $dom->getElementsByTagName('img');
    foreach ($images as $image) {
            $src = $image->getAttribute('src');
            $type = pathinfo($src, PATHINFO_EXTENSION);
            $data = file_get_contents($src);
            $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
            $image->setAttribute("src", $base64); 
    }
    $html = $dom->saveHTML();