Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Apr 22, 2010

Save html5 canvas data as image

Now when we are able to draw on web with canvas, We may feel need to save the generated image data as a image. Last night i wrote a PHP code that can do this.

Idea

The canvas.toDataURL() method returns the current image data as Data URI. And the Data URI has the image data Encodes with MIME base64. Fortunately PHP can help us with its base64_decode function that can decode the Data.
I am adding the code to force user for download it.

Code

PHP
If you are sending the canvas.toDataURL() as POST, i also tried with GET but not working(dont know why?)

$data $_POST['data'];
//removing the "data:image/png;base64," part
$uri =  substr($data,strpos($data,",")+1);
// put the data to a file
file_put_contents('wow.png'base64_decode($uri));
//force user to download the image
if(file_exists('wow.png')){
        // We'll be outputting a PNG
        header('Content-type: image/png');
        // It will be called wow.png
        header('Content-Disposition: attachment; filename="wow.png"');
        // The PDF source is in wow.png
        readfile('wow.png');
}
}


Demo

See this code working here.

Labels: ,




By :