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>
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();
Related
When I echo the following:
$im_dec = base64_decode($row['image']);
I obtain the desired URL:
https://www.ft.com/__origami/service/image/v2/images/raw/http%3A%2F%2Fprod-upp-image-read.ft.com%2F1263ad72-2d9a-11e7-9555-23ef563ecf9a?source=next&fit=scale-down&compression=best&width=210
Then I use this URL to be the src of my img:
$newImage = $dom->createElement('img');
$newImage->setAttribute("src", $im_dec);
$newImage->setAttribute("class", "articleImage");
$newTitle->appendChild($newImage);
And when I check the src attribute in my html document, I get a modified url where
& is replaced by & for example and many more weird stuff..
Some characters were modified and I don't know how to avoid it. I tried many things but I thought base64 encoding would work...
Help please!
You can convert an image to base64 encoding with the following example:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I have a string that contains text and photos as you can see bellow.
My code so far get all the images and upload them into a folder.
I need to replace the new uploaded links with the correct oreder.
$nextstep = "Hello there this is image 1 <img src='http://www.demosite.com/wp-content/uploads/2015/01.jpg' width='653' height='340' alt='xxx' title='xxx'> !! And Now you can see image number 2 <img src='http://www.demosite.com/wp-content/uploads/2015/02.jpg' width='653' height='340' alt='xxx' title='xxx'>";
$string = $nextstep;
$doc = new DOMDocument();
$doc->loadHTML($string);
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) { //STARTING LOOP
echo "</br>";
echo $image->getAttribute('src') . "\n";
echo "</br>";
$urlimg = $image->getAttribute('src'); //IMAGE URL
$URL = urldecode($urlimg);
$image_name = (stristr($URL,'?',true))?stristr($URL,'?',true):$URL;
$pos = strrpos($image_name,'/');
$image_name = substr($image_name,$pos+1);
$extension = stristr($image_name,'.');
if($extension == '.jpg' || $extension == '.png' || $extension == '.gif' || $extension == '.jpeg'){
$img = '../images/' . $image_name;
file_put_contents($img, file_get_contents($url)); //UPLOAD THEM ONE BY ONE
}
}
It's not clear what the desired outcome is here. It sounds like you want to change the src URL in your existing string to the one where you've saved the images. If this isn't the case please do try updating the question for more clarity.
Here's a simple way to break down the problem...
Step 1 - Extract the img tags from DOM using source string
$html = <<<'HTML'
Hello there this is image 1 <img src="http://www.demosite.com/wp-content/uploads/2015/01.jpg" width="653" height="340" alt="xxx" title="xxx"> !!
And Now you can see image number 2 <img src="http://www.demosite.com/wp-content/uploads/2015/02.jpg" width="653" height="340" alt="xxx" title="xxx">
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html);
$imgs = $dom->getElementsByTagName('img');
// Store the list of image urls in an array - this will come in handy later
$imgURLs = [];
foreach($imgs as $img) {
if (!$img->hasAttribute('src')) {
continue;
}
$imgURLs[] = $img->getAttribute('src');
}
Step 2 - Save the image in a different location
$newImgURLs = []; // new modified URLs where images were moved
$newPath = '../images'; // wherever you're saving the images
foreach($imgURLs as $imgURL) {
/**
* Use parse_url and pathinfo to break down the URL parts and extract the
* filename/extension instead of the fragile implementation you used above
*/
$URLparts = parse_url($imgURL);
$file = pathinfo($URLparts['path']);
$fileName = $file['filename'] . '.' . $file['extension'];
$newFileName = $newPath . '/' . $fileName;
$newImgURLs[] = $URLparts['scheme'] . '://' .
$URLparts['host'] . $file['dirname'] . '/' . $newFileName .
(isset($URLparts['query']) ? ('?' . $URLparts['query']) : null) .
(isset($URLparts['fragment']) ? ('#' . $URLparts['fragment']) : null);
// download image and save to new location
file_put_contents($newFileName, file_get_contents($imgURL));
}
Step 3 - Modify the img src URLs to new path
foreach($imgs as $i => $img) {
$img->setAttribute('src', $newImgURLs[$i]);
}
echo $dom->saveHTML(); // new updated DOM
// or just create a new $html string from scratch using the new URLs.
I'm trying to create a .pdf file with a base64 string from an image, and I can create it correctly, but when I try to open the file, the program sends a message that tells the file is corrupt or something like that..
I got this code:
define('UPLOAD_DIR', '../image/');
$img = $_POST['image'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$uniqueNumber = uniqid();
$namefile = $uniqueNumber.'.png';
$file = UPLOAD_DIR . $namefile;
$success = file_put_contents($file, $data);
$namefile = $uniqueNumber.'.pdf';
$file = UPLOAD_DIR . $namefile;
$success = file_put_contents($file, $data);
I can open the .png file correctly so, i think it's not problem from the base64 decoded string. Thank you all!
EDIT:
I'm trying this code and getting the same issue.
$data = base64_decode ($img);
//Write data back to pdf file
$pdf = fopen ('test.pdf','w');
fwrite ($pdf,$data);
//close output file
fclose ($pdf);
echo 'Done';
Is that becouse i'm saving an image with .pdf ? I think no, because if i'm doing fopen with .pdf should be with that format.
EDIT 2:
FOUND A SOLUTION.
http://www.fpdf.org/en/script/script45.php
I followed these steps and i can get that, thank you all!
Check out DOMPDF: https://github.com/dompdf/dompdf
You can definitely use DOMPDF to create a PDF with an image tag whose source is that Base64 string. and render that to PDF.
<?php
require_once("dompdf_config.inc.php");
$img = $_POST['image'];
$html =
'<html><body>'.
'<img src="'.$img.
'"></body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");
?>
I've wrote a short script to upload images from a URL so as not to hotlink to them. If the image extension is not a .jpeg then the image that is uploaded is broken. I can't figure out how to preserve the file extension or filename so I've had to add a timestamp to them and a static extension.
<?php
ini_set('user_agent', 'TEST/1.0 +http://127.0.0.1');
require_once('simple_html_dom.php');
// Create DOM from URL
$html = file_get_html('http://www.discogs.com/viewimages?release='.$_POST["album_id"]);
// Grab the coverart
$img = $html->find('.image_frame', 0);
$url = $img->src;
$file = file_get_contents($url);
$image = 'discogs_'.time().'_image.jpeg';
file_put_contents('/path/to/file/'.$image,$file);
echo $image;
?>
Updated code with Baba's help: http://codepad.org/3zH3B882
You can try using getimagesize with image_type_to_extension
require_once('simple_html_dom.php');
$url = "http://www.discogs.com/viewimages?artist=Test+%282%29";
$html = file_get_html($url);
$img = $html->find('.image_frame', 0);
$info = getimagesize($img->src);
$extention = image_type_to_extension($info[2]);
$image = 'discogs_'.time().'_image' . $extention;
echo $image ;
Output
discogs_1348438953_image.gif
I want to convert image from its url to base64.
Do you want to create a data url? You need a MIME-Type and some other additional information then (see Wikipedia). If this is not the case, this would be a simple base64 representation of the image:
$b64image = base64_encode(file_get_contents('path/to/image.png'));
Relevant docs: base64_encode()-function, file_get_contents()-function.
I got to this question searching for a similar solution, actually, I understood that this was the original question.
I wanted to do the same, but the file was in a remote server, so this is what I did:
$url = 'http://yoursite.com/image.jpg';
$image = file_get_contents($url);
if ($image !== false){
return 'data:image/jpg;base64,'.base64_encode($image);
}
So, this code is from a function that returns a string, and you can output the return value inside the src parameter of an img tag in html. I'm using smarty as my templating library. It could go like this:
<img src="<string_returned_by_function>">
Note the explicit call to:
if ($image !== false)
This is necessary because file_get_contents can return 0 and be casted to false in some cases, even if the file fetch was successful. Actually in this case it shouldn't happen, but its a good practice when fetching file content.
Try this:-
Example One:-
<?php
function base64_encode_image ($filename=string,$filetype=string) {
if ($filename) {
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
}
?>
used as so
<style type="text/css">
.logo {
background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px;
}
</style>
or
<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/>
Example Two:-
$path= 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I'm not sure, but check this example http://www.php.net/manual/es/function.base64-encode.php#99842
Regards!
base64_encode