php - 将 Canvas 图像和表单数据发送到服务器以命名为 png

标签 php javascript forms canvas

您好,我需要获取要与 Canvas 图像一起提交的表单数据。然后使用该表单数据来命名保存在服务器上的文件。我刚刚开始掌握 PHP,所以任何帮助都会很棒。

这是我的工作示例,它将把相同的命名文件保存到服务器。

HTML

 <form action="name.php" method="post">
        Name: <input type="text" name="fname">
        Age: <input type="text" name="age">
        <input type="button" onclick="saveImage();formSubmit();" value="Submit form">
 </form>

JS

function saveImage(){
var xmlhttp;
xmlhttp=((window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"));
xmlhttp.onreadystatechange=function()
{
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        //do something with the response
    }
}
xmlhttp.open("POST","upload.php",true);
var oldCanvas = document.getElementById('colors_sketch').toDataURL("image/png");
var img = new Image();
img.src = oldCanvas;
xmlhttp.setRequestHeader("Content-type", "application/upload")
xmlhttp.send(oldCanvas);

}

PHP

$data = file_get_contents('php://input');

$canvasImg = imagecreatefrompng($data);
$width  = imagesx($canvasImg);
$height = imagesy($canvasImg);

$outImg = imagecreatetruecolor($width, $height);
$color = imagecolorallocatealpha($outImg, 255, 255, 255, 127);
imagefill($outImg, 0, 0, $color);
imagecopy($outImg, $canvasImg, 0, 0, 0, 0, $width, $height);

imagepng($outImg, 'test.png');

最佳答案

以下是将表单和图像发送到 upload.php 的步骤

首先创建一个要发送的数据包,其中包括序列化图像和表单。这里我使用jquery来序列化你的表单(或者不用jquery自己序列化)。

// serialize and concatenate both form and canvas image
var package=$("form").serialize() + "&imageDataURL="+canvas.toDataURL();

然后使用 AJAX 将其 POST 到您的 PHP 服务器:

// ajax it
postImagePlusForm();

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

最后捕获它并在 php 中处理它:

<?php 
if ( isset($_POST["imageDataURL"]) && !empty($_POST["imageDataURL"]) ) {    
    // create $dataURL
    $dataURL = $_POST["imageDataURL"];  
    // Extract base64 data
    // we have an unneeded header, zap it
    $parts = explode(',', $dataURL);  
    $data = $parts[1];  
    // Decode
    $data = base64_decode($data);  
    // Save
    $fp = fopen('newImage.png', 'w');  
    fwrite($fp, $data);  
    fclose($fp); 
}
if ( isset($_POST["formData"]) && !empty($_POST["formData"]) ) {    
    $formData = $_POST['formData'];
    foreach ($formValue as $x) {
        // do whatever you need to do with each form value ($x)
    }
}

关于php - 将 Canvas 图像和表单数据发送到服务器以命名为 png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16148371/

相关文章:

php json_encode 没有返回正确的 json 编码字符串

javascript - 是否应该在应用程序逻辑处理输入数据对象之前对其进行克隆?

javascript - jQuery 冒号选择器

python-3.x - 将数据从 django 表单传递到 ListView

php - 保存实体形式错误 - symfony2

javascript - 如何在重新加载页面后隐藏模态并显示另一个模态?

php - 选择所有数据而不是id

javascript - 使用 Flot 绘制事件持续时间图表

javascript - 使用数据库结果数组 codeigniter 填充 html 表单

javascript - 相同字符串的 SHA256 不同值