简体   繁体   中英

Can't save full canvas image to server

I am having a problem saving a canvas image to my server. I have tried multiple things and the only thing that seems to work right now is using one suggestion I found looking around which was to fill a hidden text field in a form and submit it to my php page that can take the post and convert it and save it on the server. While this does work, it is only posting 1/8th of the image.

When I check the toDataURL() contents it is the same amount of data that is passed on to the PHP page so I'm not sure where the image is getting chopped up and the image size only ends up about 380kb.

Here is what I have:

Javascript:

var canvas = document.getElementById("myCanvas");
var image = canvas.toDataURL();
document.getElementById("savecarddata").value = image;

PHP

$upload_dir = 'mydirectory'; 
$img = $_POST['savecarddata'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir.rand().".png";
$success = file_put_contents($file, $data);

This does save the image but only the top of it. I've tried ajax but I can't seem to get it to work right so this was the next best solution for me. I would love any help!

Thanks in advance!

This is how I did it:

Using ajax

 var canvas = document.getElementById("myCanvas");
    var canvasData = canvas.toDataURL('image/png');
    var ajax = new XMLHttpRequest();            
    var postdata='saveimage.php';
    ajax.open('POST', postdata, false);
    ajax.setRequestHeader('Content-Type', 'application/upload');
    ajax.send(canvasData);  

then in saveimage.php

if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$imgdata = $GLOBALS['HTTP_RAW_POST_DATA'];

    $filteredData=substr($imgdata, strpos($imgdata, ",")+1);// Remove the headers (data:,) part.
    $data = base64_decode($filteredData);//decode data
    $im = imagecreatefromstring($data); //create image
    if ($im !== false) { 
        imagesavealpha($im, true);
        imagepng($im, "result.png",9); 
    }
    else {
        echo 'An error occurred.';
    }

    }

you can also pass arguments as GET variables in the ajax

var postdata="saveimage.php?imagename=" + document.getElementById("someFeild").value;

I don't know if it's relevant but check how you set the canvas width and height. You should set them inside the canvas tag.

<canvas width='yourValue' height='yourValue'></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM