問題描述
我在使用使用 canvas 的 todataurl() 方法創建的數據時遇到困難.目前,我的代碼將結果數據發送到我的 php 服務器,該服務器使用 file_put_contents() 方法創建一個文件來存儲該數據.現在,如果我將文件中產生的亂碼剪切并粘貼到圖像標簽 src 中,它可以正常工作并正確顯示,因此我認為到目前為止一切都很好.
I'm having difficulty using data created with canvas's todataurl() method. Currently my code sends the resulting data to my php server which uses the file_put_contents() method to create a file to store that data. Now if I cut and paste the resulting gibberish from the file into an image tag src it works fine and displays properly so I assume so far everything is peachy.
但是當我嘗試在 JS 中使用代碼時,我一直遇到問題.我試過 php 的 base64_decode 方法,但一直收到損壞的文件.我找到了這個代碼:
But I keep running into issues when I try to use the code in JS. I've tried php's base64_decode method but kept getting currupt files. I found this code:
<?php
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
并且仍然有損壞的文件.理想情況下,我想用它創建一個 .png 文件,但我只想在 JS 中再次處理數據文件.非常感謝任何幫助.
and still got currupted files. Ideally I'd like to create a .png file with it but I'd settle for just processing the data file again in JS. Any help greatly appreciated.
推薦答案
看來您必須通過 toDataURL()
函數刪除預先添加到圖像數據的標題.在客戶端,您可以像這樣去除標題:
It seems you have to get rid of the header that is prepended to the image data by the toDataURL()
function.
On the client side you can strip off the header like this:
..
var data=canvas.toDataURL();
var output=data.replace(/^data:image/(png|jpg);base64,/, "");
// now send "output" to the server
..
在服務器端使用這個:
<?php
$decocedData = base64_decode($encodedData);
?>
這篇關于將畫布解碼為 dataURL的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!