Html2canvas save image not working

I am showing a screenshot with html2canvas 0.4.0 and want to save it as an image on my web server.

For this, I wrote the following function:

Javascript

function screenShot(id) { html2canvas(id, { proxy: "https://html2canvas.appspot.com/query", onrendered: function(canvas) { $('body').append(canvas); // This works perfect... var img = canvas.toDataURL("image/png"); var output = img.replace(/^data:image\/(png|jpg);base64,/, ""); var Parameters = "image=" + output + "&filedir=" + cur_path; $.ajax({ type: "POST", url: "inc/saveJPG.php", data: Parameters, success : function(data) { console.log(data); } }).done(function() { }); } }); } 

saveJPG.php

 <?php $image = $_POST['image']; $filedir = $_POST['filedir']; $name = time(); $decoded = base64_decode($image); file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX); echo $name; ?> 

After rendering the canvas, I can perfectly add it to the body of the HTML, but saving it on my server leads to a damaged (?) File.

I can read sizes in IrvanView, but is the image transparent / empty? The file is approximately 2.076 KB in size. So it really is not empty.

I also tried this with JPEG, and this leads to a damaged file, and IrfanView says something like "dummy marker length".

The screenshot is 650x9633. How much data is there for the POST method?

+4
source share
1 answer

If someone stumbles on the same problem, here is how I solved it:

The problem depended on the fact that + in URLs is interpreted as coded space (e.g. %20 ) for most servers. So I first needed to encode the data first, and then send it via POST to my designated PHP function.

Here is my code:

Javascript

 function screenShot(id) { html2canvas(id, { proxy: "https://html2canvas.appspot.com/query", onrendered: function(canvas) { var img = canvas.toDataURL("image/png"); var output = encodeURIComponent(img); var Parameters = "image=" + output + "&filedir=" + cur_path; $.ajax({ type: "POST", url: "inc/savePNG.php", data: Parameters, success : function(data) { console.log("screenshot done"); } }).done(function() { //$('body').html(data); }); } }); } 

savePNG.php

 <?php $image = $_POST['image']; $filedir = $_POST['filedir']; $name = time(); $image = str_replace('data:image/png;base64,', '', $image); $decoded = base64_decode($image); file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX); echo $image; ?> 

Hooray!

+15
source

Source: https://habr.com/ru/post/1491601/


All Articles