javascript 如何将画布标签中的图像保存到 php 服务器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13804683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:49:42  来源:igfitidea点击:

How save image from canvas tag to php server?

phpjavascriptajaxhtml

提问by open source guy

I have a javascript code like this

我有一个这样的 javascript 代码

var testCanvas = document.getElementById('canvas-1');
var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'http://www.domain.com/imgsave.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.send("canvasData"+canvasData );

My php code is like this

我的php代码是这样的

if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
    // Get the data
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

    $filteredData=substr($imageData, strpos($imageData, ",")+1);

    $unencodedData=base64_decode($filteredData);
    $fp = fopen( 'test.png', 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );
        echo "saved";
}
  else{

  echo "no raw data";
  }

When executing this code i got a zero size png file image? Whats the problem with my code?

执行此代码时,我得到了一个零大小的 png 文件图像?我的代码有什么问题?

回答by FunkyMonk91

I had to do this recently myself.

我最近不得不自己做这件事。

First I put my canvasData into a hidden field and posted it to my PHP page.

首先,我将 canvasData 放入隐藏字段并将其发布到我的 PHP 页面。

It comes back in this format: data:image/png;base64,iVBORw0......

它以这种格式返回: data:image/png;base64,iVBORw0......

You need to split the data up first, as this: data:image/png;base64,is header information. The rest is the encoded data.

您需要先拆分数据,因为:data:image/png;base64,是标题信息。其余的是编码数据。

$rawData = $_POST['imageData'];
$filteredData = explode(',', $rawData);

$unencoded = base64_decode($filteredData[1]);

I then create the image on my server:

然后我在我的服务器上创建图像:

//Create the image 
$fp = fopen('sigs/test1.png', 'w');
fwrite($fp, $unencoded);
fclose($fp); 

And then read it to do whatever I want with it.

然后阅读它以做任何我想做的事情。

$file_name = 'test1.png';
$file_size = strlen($filteredData[1])/1024; //This may be wrong, doesn't seem to break for me though.


$fh = fopen('sigs/test1.png', 'r');
$content = fread($fh, $file_size);
$content = base64_encode($content);
fclose($fh);

I'm more than sure there is a much more elegant solution to this, but this has been working for me!

我非常确定有一个更优雅的解决方案,但这对我有用!

Check this for more info (possibly): My own question

检查更多信息(可能):我自己的问题

回答by Ruslan Polutsygan

Here is what I do save image from canvas via ajax. I use jQuery on client side

这是我通过ajax从画布保存图像的方法。我在客户端使用 jQuery

 jQuery.ajax({
     url: 'save.php',
     type: 'POST',
     data: {
         data: c.toDataURL('image/png')
     },
     complete: function(data, status)
     {
         if(status=='success')
         {
            alert('saved!');
         }
         alert('Error has been occurred');
     }

 });

php:

php:

    $based64Image=substr($_POST['data'], strpos($_POST['data'], ',')+1);

    $image = imagecreatefromstring(base64_decode($based64Image));

    $fileName='';
    if($image != false)
    {
        $fileName=time().'.png';
        if(!imagepng($image, $fileName))
        {
//          fail;
        }
    }
    else
    {
//          fail;
    }

I hope this helps.

我希望这有帮助。

回答by Jeremy Harris

According to a comment in the manual, to get the HTTP_RAW_POST_DATA, you need to do something like this:

根据手册中注释,要获取 HTTP_RAW_POST_DATA,您需要执行以下操作:

<?php $postdata = file_get_contents("php://input"); ?> 

The manual says this about the wrappers such as php://input:

该手册对包装器进行了说明,例如php://input

In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives.

对于 POST 请求,最好使用 php://input 而不是 $HTTP_RAW_POST_DATA,因为它不依赖于特殊的 php.ini 指令。