I have a 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 i got a zero size png file image? Whats the problem with my code?
I had to do this recently myself.
First I put my canvasData into a hidden field and posted it to my PHP page.
It comes back in this format: data:image/png;base64,iVBORw0......
You need to split the data up first, as this: data:image/png;base64,
is header information. The rest is the encoded data.
$rawData = $_POST['imageData'];
$filteredData = explode(',', $rawData);
$unencoded = base64_decode($filteredData[1]);
I then create the 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 with it.
$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'm more than sure there is a much more elegant solution to this, but this has been working for me!
Check this for more info (possibly): My own question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With