4

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/

j0k
  • 22,600
  • 28
  • 79
  • 90
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378

1 Answers1

7

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));
jwueller
  • 30,582
  • 4
  • 66
  • 70
  • Thanks for your answer! Now the image is valid! But only has the background, the text is missing... any idea why? (you can test it in the link, If you want ^^) – Toni Michel Caubet Mar 30 '13 at 17:29
  • 1
    @ToniMichelCaubet: Missing image content is probably a client-side issue here. It looks like html2canvas isn't exactly perfect in terms of replicating the HTML in an image. Is the text present when displaying the image using the disabled line `$('.imageHolder').append('');`? – jwueller Mar 30 '13 at 17:33
  • I believe you are right... Actually if I select a color for the text in the wyswyg it does put the content in the image... Well this is not the question anymore but If you have any thoughts.. :) – Toni Michel Caubet Mar 30 '13 at 17:39