将图像保存在服务器错误

时间:2016-06-29 11:31:58

标签: javascript php jquery ajax

我有一个ajax函数来获取div并将其制作图片然后将其发布到php上以保存它。

<script>
 $("#capture").click(function() { 
html2canvas([document.getElementById('printableArea')], {
    onrendered: function (canvas) {
        var imagedata = canvas.toDataURL('image/png');
        var imgdata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
        //ajax call to save image inside folder
        $.ajax({
            url: 'save_image.php',
            data: {
                   imgdata:imgdata
                   },
            type: 'post',
            success: function (response) {   
               console.log(response);
               $('#image_id img').attr('src', response);
            }
        });
    }
})
 });
</script>

然后我将保存图像php保存在服务器上

<?php
$imagedata = base64_decode($_POST['imgdata']);
$filename = md5(uniqid(rand(), true));
//path where you want to upload image
$file = '/home/a7784524/public_html/barcodeimage/'.$filename.'.png';
$imageurl  = 'http://panosmoustis.netai.net/barcodeimage/'.$filename.'.png';
file_put_contents($file,$imagedata);
echo $imageurl;

?>

我的问题是虽然当我尝试打开它时图像保存在路径上但是我得到错误图像无法显示,因为它包含错误 谢谢

1 个答案:

答案 0 :(得分:0)

@aristeidhsP请检查file_put_contents返回;是真的创造了图像吗? 如果是这样,你必须检查$ imagedata的内容:你是否正确地从图像数据中剥离了额外的东西(你的正则表达式可能不会在jpeg或gif扩展名上触发)。 希望这有帮助