带有html2canvas的div的屏幕截图。发送到PHP,保存:损坏的图像

时间:2013-03-30 17:20:09

标签: php png base64 html2canvas

我生成画布并将其传递给php,所以:

$('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);
?>

问题是生成图像,当我点击下载链接时,下载被伪造但图像无法打开(似乎已损坏)

我错过了什么?

可在此处测试:http://toniweb.us/div2img/

1 个答案:

答案 0 :(得分:7)

您应该base64_decode()数据网址。它甚至在URL本身中说明了它:data:image/png;base64,...

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