使用表单发送画布,创建PNG并命名

时间:2013-04-25 11:18:10

标签: php javascript html forms canvas

我打算将画布图像和表单信息一起发送到服务器。然后,这将保存一个以表格中的信息命名的PNG。

目前写入的PNG无法打开,只是一个0 kb的混乱文件。

完整网站为here



HTML - 写入信息并在提交时激活javascript的表单

<form action="PHPtestupload.php" method="post">
  Name <input type="text" name="name" value="" style="width:230px;  margin-left: -160px; font-size:1em; "/>
  Email <input type="email" name="email" value="" style="width:230px;  margin-top: 12px; margin-left: -160px; font-size:1em; "/>

  <input type="submit" onclick="postImagePlusForm();" value="Submit" style=" opacity:1; -webkit-appearance: none; width:100px; height:50px; margin-left: -50px;">
</form>



JS

    // sends image to server
    // serialize your canvas
    var dataURL=document.getElementById('colors_sketch').toDataURL('image/png');

    // serialize your form
    var str = $("form").serializeArray();

    // wrap both in an object
    var package={ formData: str, imageDataURL: dataURL }




    // ajax it 
    postImagePlusForm();

    function postImagePlusForm(){
    $.ajax({  
     type: "POST",  
     url: "PHPtestupload.php",  
     data: package,  
     success: function(value) {  
        // ...we have success!
    }
   });
  }



PHP

    $dataURL = $_POST["imageDataURL"];
    $dataURL = str_replace('data:image/png;base64,', '', $dataURL);
    $dataURL = str_replace(' ', '+', $dataURL);
    $image = base64_decode($dataURL);
    $filename = 'newImage.png';
    file_put_contents('image/' . $filename, $image);

    $name = $_POST["formData"];
    $target = 'newImage.png';
    rename($target, $newName);

1 个答案:

答案 0 :(得分:0)

这对我有用,图片字符串取自您的网站

<?php
header("Content-type: image/png");
echo base64_decode("iVBORw0KGgoAAAANSUhEUgAAAlgAAAJECAYAAADKclo8AAAFXElEQVR4nO3BMQEAAADCoPVPbQ0PoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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