Toni Michel Caubet
Toni Michel Caubet

Reputation: 20173

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

I generate the canvas and pass it to php so:

$('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 thing is that the image is generated, when I click the download link the download is forzed but the image cannot be opened (seems to be corrupted)

What am I missing?

It can be tested here: http://toniweb.us/div2img/

Upvotes: 4

Views: 8924

Answers (1)

jwueller
jwueller

Reputation: 31006

You should probably base64_decode() the data URL. It even says it in the URL itself: data:image/png;base64,...

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

Upvotes: 7

Related Questions