Save a Base64 Encoded Canvas image to a png file using PHP


This and the next post will demonstrate how to draw on a canvas and then save the file on a server using PHP. Here is the very simple server side code:

<?php
// requires php5
define(‘UPLOAD_DIR’, ‘images/’);
$img = $_POST[‘img’];
$img = str_replace(‘data:image/png;base64,’, ”, $img);
$img = str_replace(‘ ‘, ‘+’, $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . ‘.png’;
$success = file_put_contents($file, $data);
print $success ? $file : ‘Unable to save the file.’;
?>

The next post will be the slightly more complicated front-end code. This was particularly designed for a Sencha Touch iPad app that will allow people to sign with their finger. It has some flaws, but the basics are pretty reusable and good!

Your result may look something like this:

Copy from http://j-query.blogspot.fr/2011/02/save-base64-encoded-canvas-image-to-png.html
Advertisements
By dbglory Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s