简体   繁体   中英

php canvas to image on server

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

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!

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