How to save image from canvas tag to php server?

I have javascript code like this

var testCanvas = document.getElementById('canvas-1'); var canvasData = testCanvas.toDataURL("image/png"); var ajax = new XMLHttpRequest(); ajax.open("POST",'http://www.domain.com/imgsave.php',true); ajax.setRequestHeader('Content-Type', 'canvas/upload'); ajax.send("canvasData"+canvasData ); 

My php code is like this

 if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) { // Get the data $imageData=$GLOBALS['HTTP_RAW_POST_DATA']; $filteredData=substr($imageData, strpos($imageData, ",")+1); $unencodedData=base64_decode($filteredData); $fp = fopen( 'test.png', 'wb' ); fwrite( $fp, $unencodedData); fclose( $fp ); echo "saved"; } else{ echo "no raw data"; } 

When executing this code, did I get a PNG image with a zero size? What is the problem with my code?

+4
source share
3 answers

I should have done this recently.

First, I put canvasData in a hidden field and placed it on my PHP page.

It returns in this format: data:image/png;base64,iVBORw0......

First you need to break the data, as this is: data:image/png;base64, is the header information. The rest is encoded data.

 $rawData = $_POST['imageData']; $filteredData = explode(',', $rawData); $unencoded = base64_decode($filteredData[1]); 

Then I create an image on my server:

 //Create the image $fp = fopen('sigs/test1.png', 'w'); fwrite($fp, $unencoded); fclose($fp); 

And then read it to do whatever I want.

 $file_name = 'test1.png'; $file_size = strlen($filteredData[1])/1024; //This may be wrong, doesn't seem to break for me though. $fh = fopen('sigs/test1.png', 'r'); $content = fread($fh, $file_size); $content = base64_encode($content); fclose($fh); 

I am more than sure that there is a much more elegant solution, but it works for me!

Check this out for more info (maybe): My own question

+6
source

Here is what I do to save the image from the canvas via ajax. I am using jQuery on the client side

  jQuery.ajax({ url: 'save.php', type: 'POST', data: { data: c.toDataURL('image/png') }, complete: function(data, status) { if(status=='success') { alert('saved!'); } alert('Error has been occurred'); } }); 

PHP:

  $based64Image=substr($_POST['data'], strpos($_POST['data'], ',')+1); $image = imagecreatefromstring(base64_decode($based64Image)); $fileName=''; if($image != false) { $fileName=time().'.png'; if(!imagepng($image, $fileName)) { // fail; } } else { // fail; } 

Hope this helps.

+2
source

According to the comment in the manual , to get HTTP_RAW_POST_DATA, you need to do something like this:

 <?php $postdata = file_get_contents("php://input"); ?> 

The manual talks about wrappers like php://input :

In the case of POST requests, it is preferable to use the php: // input instead of $ HTTP_RAW_POST_DATA, since it does not depend on the special php.ini Directive.

0
source

All Articles