Screenshot of a div with html2canvas. Sent to php, saved: damaged image

I create a canvas and pass it to php like this:

$('body').on('click','#save_image',function(){ html2canvas($('.myImage'), { onrendered: function(canvas) { //$('.imageHolder').html(canvas); var dataURL = canvas.toDataURL("image/png"); // $('.imageHolder').append('<img src="'+dataURL+'" />'); $('.imageHolder').html('Generating..'); $.post('image.php',{image: dataURL},function(data){ $('.imageHolder').html(data); }); } }); }); 

image.php:

 <? $image = $_POST['image']; echo "<img src='$image' alt='image' />"; $decoded = str_replace('data:image/png;base64,','',$image); $name = time(); file_put_contents("/home/toni005/public_html/toniweb.us/div2img/" . $name . ".png", $decoded); echo '<p><a href="download.php?img='.$name.'.png">Download</a></p>'; ?> 

download.php:

  <? $file = $_GET['img']; header('Content-Description: File Transfer'); header("Content-type: image/jpg"); header("Content-disposition: attachment; filename= ".$file.""); readfile($file); ?> 

The fact is that the image is generated when I click on the download link that downloads, but the image cannot be opened (it seems to be damaged)

What am I missing?

Here you can test: http://toniweb.us/div2img/

+4
source share
1 answer

You should base64_decode() specify the data url. He even talks about it in the URL itself: data:image/png;base64,...

 $decoded = base64_decode(str_replace('data:image/png;base64,', '', $image)); 
+7
source

All Articles