Home >Backend Development >PHP Tutorial >Why Are My HTML5 Canvas Images Corrupted When Saving to the Server?
After following online tutorials, attempts to save an HTML5 Canvas as an image on the server result in corrupted or empty files. The cause remains unknown.
1. Configure the XMLHttpRequest correctly:
var xmlHttpReq = false; if (window.XMLHttpRequest) { ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { ajax = new ActiveXObject("Microsoft.XMLHTTP"); }
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
2. Modify the PHP Script:
if ($fp) { fwrite($fp, $unencodedData); fclose($fp); }
JavaScript
function saveImage() { var canvasData = canvas.toDataURL("image/png"); var xmlHttpReq = false; if (window.XMLHttpRequest) { ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } ajax.open("POST", "testSave.php", false); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.onreadystatechange = function() { console.log(ajax.responseText); } ajax.send("imgData=" + canvasData); }
PHP
<?php if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) { $imageData = $GLOBALS['HTTP_RAW_POST_DATA']; $filteredData = substr($imageData, strpos($imageData, ",")+1); $unencodedData = base64_decode($filteredData); if ($fp = fopen('/path/to/file.png', 'wb')) { fwrite($fp, $unencodedData); fclose($fp); } } ?>
The above is the detailed content of Why Are My HTML5 Canvas Images Corrupted When Saving to the Server?. For more information, please follow other related articles on the PHP Chinese website!