Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

php - Decoding a canvas todataURL

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.

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);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
..

On the server side use this:

<?php
    $decocedData = base64_decode($encodedData);
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...