LMSouq
server-admin Open

How to save an HTML5 Canvas as an image on a server?

NA
nathan lachenmyer
1 month ago
3 views
Problem Description
I'm working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is: * Create an image on an HTML5 Canvas using a generative algorithm * When the image is completed, allow users to save the canvas as an image file to the server * Allow the user to either download the image or add it to a gallery of pieces of produced using the algorithm. However, I’m stuck on the second step. After some help from Google, I found this [blog post][1], which seemed to be exactly what I wanted: Which led to the JavaScript code: function saveImage() { var canvasData = canvas.toDataURL("image/png"); var ajax = new XMLHttpRequest(); ajax.open("POST", "testSave.php", false); ajax.onreadystatechange = function() { console.log(ajax.responseText); } ajax.setRequestHeader("Content-Type", "application/upload"); ajax.send("imgData=" + canvasData); } and corresponding PHP (testSave.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); $fp = fopen('/path/to/file.png', 'wb'); fwrite($fp, $unencodedData); fclose($fp); } ?> But this doesn’t seem to do anything at all. More Googling turns up this [blog post][2] which is based off of the previous tutorial. Not very different, but perhaps worth a try: $data = $_POST['imgData']; $file = "/path/to/file.png"; $uri = substr($data,strpos($data, ",") + 1); file_put_contents($file, base64_decode($uri)); echo $file; This one creates a file (yay) but it’s corrupted and doesn’t seem to contain anything. It also appears to be empty (file size of 0). Is there anything really obvious that I’m doing wrong? The path where I’m storing my file is writable, so that isn’t an issue, but nothing seems to be happening and I’m not really sure how to debug this. ### Edit Following Salvidor Dali’s link I changed the AJAX request to be: 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...

AI-Generated Solution

Powered by LMSouq AI · GPT-4.1-mini

✓ Solution Ready
Analyzing problem and generating solution…
Was this solution helpful?
Back to Knowledge Base