Reputation: 74
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>
Upvotes: 0
Views: 2749
Reputation: 11
azjezz's answer helped me a lot, but I had to add the following line of code to get the images viewable on word 365: $html = preg_replace("/<img src="data:image/;base64,/", '<img src="data:image/png;base64,', $html);
Upvotes: 0
Reputation: 3987
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();
Upvotes: 3