canvas..toDataURL and upload it


canvas..toDataURL and upload it

我正在努力将画布转换为图像,并在用户提交表单时将其上传到服务器。图像已正确发布,但在服务器中显示为空。

这是我的代码,(我使用phonegap) .drawImage ()主要是.js..但canvas..toDataURL在 HTML 中的脚本中

 <script>
 function insert()
 {
var img = document.getElementById("myCanvas")[0].toDataURL("image/jpeg");
$.ajax({
type: "POST",
url: "http://*******************/create.php?title="+      ($("#myTitle").val())+"&description="
+$("#myDesc").val()+"&price="+$("#myPrice").val(),
data: {img: img},
success: function(data)
{
    alert("inserted");
}});
</script>

.php

$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.'; 

知道吗?

编辑!!!

最后是上加载

!!

感谢杰克·弗兰岑的建议。我已将 php 代码更改为

$img = $_POST['img'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.jpg';
$success = file_put_contents($file, $data);

它正在发挥魅力! :)

我知道

你的问题!您的PHP代码正在寻找"PNG",但您的JavaScript正在生成"JPG"

只需切换到 DataURL("image/jpeg") 到 toDataURL()