How save image from canvas tag to php server?

前端 未结 3 1322
无人共我
无人共我 2021-01-06 05:22

I have a javascript code like this

var testCanvas = document.getElementById(\'canvas-1\');
var canvasData = testCanvas.toDataURL(\"image/png\");
var ajax = n         


        
相关标签:
3条回答
  • 2021-01-06 05:58

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

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

    The manual says this about the wrappers such as 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.

    0 讨论(0)
  • 2021-01-06 06:14

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

     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:

        $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.

    0 讨论(0)
  • 2021-01-06 06:17

    I had to do this recently myself.

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

    It comes back in this format: 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.

    $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

    0 讨论(0)
提交回复
热议问题