我在使用canvas的todataurl()方法创建的数据时遇到了困难。目前我的代码将结果数据发送到我的php服务器,该服务器使用file_put_contents()方法创建一个文件来存储该数据。现在,如果我将文件中产生的乱码剪切并粘贴到图像标签src中,它可以正常工作并正确显示,所以我假设到目前为止一切都很好。
但是当我尝试在JS中使用代码时,我一直遇到问题。我已经尝试过php的base64_decode方法,但不断收到破坏的文件。我找到了这段代码:
<?php
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
仍然有被破坏的文件。理想情况下,我想用它创建一个.png文件,但我决定只在JS中再次处理数据文件。任何帮助非常感谢。
答案 0 :(得分:13)
似乎你必须摆脱toDataURL()
函数预先添加到图像数据的标题。
在客户端,您可以像这样剥离标题:
..
var data=canvas.toDataURL();
var output=data.replace(/^data:image\/(png|jpg);base64,/, "");
// now send "output" to the server
..
在服务器端使用:
<?php
$decocedData = base64_decode($encodedData);
?>
答案 1 :(得分:3)
在java脚本中,在支持此方法的浏览器上发送canvas.toDataURL()的结果,默认类型为“image / png”。
var imageInfo = canvas.toDataURL();
// now send "imageInfo" to the server
创建png文件的直接方法:
<?php
$imageInfo = imageInfoFromBrowser(); // Your method to get the data
$image = fopen($imageInfo, 'r');
file_put_contents("fileName.png", $image);
fclose($image);
?>
我在PHP 5.3 / Windows中使用它,对于其他版本,请检查。
用于在PHP上测试的图像数据样本。
$imageInfo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMYAAAC0CAYAAADPcVOXAAAHx0lEQVR4Xu2dPY5dRRBGsUSI+Umdk2KQQwfMsAHERtgDrABYgCMvADJHYIeOLDZBhgjJgG6JKz2PZ+bVu7f6666qM1LLI03frqpTfd79mfF7D97jCwIQeIfAA5hAAALvEkAMdgUEbiGAGGwLCCAGewACNgKcMWycmFWMAGIUazjl2gggho0Ts4oRQIxiDadcGwHEsHFiVjECiFGs4ZRrI4AYNk7MKkYAMYo1nHJtBBDDxolZxQggRrGGU66NAGLYODGrGAHEKNZwyrURQAwbJ2YVI4A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MfdxGHPVPW/RVG9cjFmfNywggxmW8Rs3ePl+w9wMxRlG+YF3EuADW4Knbh8W/uSUOn3U+GP7N5RFDDPwk3PP2/aMb4funoN72dVMWRBncN8QYDPie5V+3n/29M/zVzuM4zEgAMYygmFaLAGLU6jfVGgkghhEU02oRQIxa/aZaIwHEMIJiWi0CiFGr31RrJIAYRlBMq0UAMWr1m2qNBP4DoE6utZfjM60AAAAASUVORK5CYII="
答案 2 :(得分:2)
另一个重要的注意事项是你必须将空白转换为加号。如果不这样做,则解码数据已损坏:
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
了解更多信息
答案 3 :(得分:0)
其他解决方案对我不起作用。
这有效:
//image sample
$baseFromJavascript = "data:image/png;base64,BBBFBfj42Pj4";
// remove the part that we don't need from the provided image and decode it
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $baseFromJavascript));