0

I want to take the image data from my canvas on the client and save it as a .png on my server.

This is the code on my client that gets the image data from the canvas and sends it to saveImage.php:

function render()
    {

        var imageData = ctx.canvas.toDataURL("image/png");
        var postData = "imageData="+imageData;

        var ajax = new XMLHttpRequest();
        ajax.open("POST","saveImage.php",true);
        ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        ajax.onreadystatechange=function()
        {
            console.log(ajax.responseText);
        }

        ajax.send(postData);
    }

And this is what saveImage.php looks like:

    <?php
    if(isset($_POST["imageData"]))
    {
        $imageEncoded = $_POST["imageData"];

        $imageDataExploded = explode(',', $imageEncoded);

        $imageDecoded = base64_decode($imageDataExploded[1]);

        $filename = time()."image".mt_rand();

        $file = fopen("./".$filename.".png","wb");
        fwrite($file, $imageDecoded);
        fclose($file);
        echo $filename;
        exit();
    }
?>

The code actually works fine, my problem is just that the images that gets created are faulty in some way. When I try to open one, windows says that it cant show me the image because it doesn't support the format? even though its a .png?

what am I doing wrong here?

  • Have you looked into the file context with a text editor or a hex editor and compared that to the original file? What are the differences that you see? – Artjom B. Feb 18 '17 at 18:57

2 Answers2

0

Have you checked what is actually being sent over HTTP? $imageEncoded probably starts with data:image/png;base64,xxxxx

Strip everything up to the comma after base64:

https://stackoverflow.com/a/15153931/3766670

Community
  • 1
  • 1
Ruben Vincenten
  • 807
  • 4
  • 7
  • I edited the script to remove the "data:image/png;base64," but it still doesn't work :( –  Feb 18 '17 at 18:36
0

You should be encoding your data with encodeURIComponent() before including it in POST data.

You should also be using a framework like jQuery to account for browser differences. I guarantee that code will not work the same in all browsers.

On the PHP, try looking into file_put_contents() for writing data. Much quicker to type!

miken32
  • 42,008
  • 16
  • 111
  • 154