Saving a data URL from Javascript in PHP through Ajax

857 views Asked by At

For my project I need to save what's displayed on a canvas to a database. I am now quite familiar with the toDataURL() function, and the code below (essentially just a test) works, displaying the image twice.

var canvas = document.getElementById('canvas');
var image = new Image();
image.src = "03Jun15.jpg";
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext("2d").drawImage(image, 0, 0);

var newcanvas = document.getElementById('newcanvas');
var img = new Image();
img.src = canvas.toDataURL("image/png");
var imageData = canvas.toDataURL("image/png");
newcanvas.width = img.naturalWidth;
newcanvas.height = img.naturalHeight;
newcanvas.getContext("2d").drawImage(img, 0, 0);

The problems arise however when I try and save source to a session variable via Ajax. This code below comes directly after the code above and it displays nothing on the testcanvas canvas. What I want to happen is for $_SESSION['imageData'] to be set to the data URL and then the image will be displayed again, but this time using the session variable as the source. What I get for the session variable though is a long string that is very similar to the original source variable, but apparently does not match it (I have done a quick if statement to confirm this).

$.ajax({
    url:"upload_image.php",
    method:"POST",
    data:{imageData:imageData}
});

var testcanvas = document.getElementById('testcanvas');
var newimage = new Image();
newimage.src = "<?php echo $_SESSION['imageData']; ?>";
var newsource = "<?php echo $_SESSION['imageData']; ?>";
testcanvas.width = newimage.naturalWidth;
testcanvas.height = newimage.naturalHeight;
testcanvas.getContext("2d").drawImage(newimage, 0, 0);

This is what is found on upload_image.php:

session_start();

$_SESSION['imageData'] = $_POST['imageData'];

I honestly don't know what's being lost in translation here, so could someone please help?

1

There are 1 answers

1
C. Geek On

Found this for you: https://gist.github.com/peterschmidler/2410299

The following code saves a canvas as png with ajax to php.

Javascript:

var canvasData = canvasElement.toDataURL("image/png");
$.ajax({
    url:'save.php', 
    type:'POST', 
    data:{
        data:canvasData
    }
});

PHP:

$data = $_POST['data'];
$data = substr($data,strpos($data,",")+1);
$data = base64_decode($data);
$file = 'output.png';
file_put_contents($file, $data);
echo "Success!";