2016-06-29 26 views
1

我有一個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; 

?> 

我的問題是,雖然圖像被保存在路當我嘗試打開它,我得到錯誤的圖像不能顯示,因爲它包含錯誤 謝謝

+0

你確定你的正則表達式是「有效的」?你試過用''分割數據嗎? (逗號不用於base64) –

+0

你是什麼意思正則表達式? – aristeidhsP

+0

'/^data:image \ /(png | jpg); base64,/'是一個正則表達式 –

回答

0

@aristeidhsP請檢查file_put_contents返回;是真正創造的形象? 如果是這樣,你必須檢查$ imagedata的內容:你是否正確地從圖像數據中剝離了額外的東西(你的正則表達式可能無法在jpeg或gif擴展上觸發)。 希望這有助於