Rename an image created using an HTML5 canvas

I made a simple canvas and saved it as an image. I did this with this code:

var canvas = document.getElementById("mycanvas"); var img = canvas.toDataURL("image/png"); 

and create the created image as follows:

 document.write('<img src="'+img+'"/>'); 

But his name is always strange. I want to rename the image name, for example faizan.jpg , etc. How to do it?

+4
source share
2 answers

Simply put, you cannot. When you call the toDataURL method in an HTMLCanvasElement, it generates a string representation of the image as a data URL. Thus, if you try to save the image, the browser will give it the default file name (for example, Opera will save it as default.png if the data URL was a png file).

There are many workarounds. The easiest way is to make an AJAX call on the server, save the image on the server side and return the URL of the saved image, which can then be retrieved and saved on the client side:

 function saveDataURL(canvas) { var request = new XMLHttpRequest(); request.onreadystatechange = function () { if (request.readyState === 4 && request.status === 200) { window.location.href = request.responseText; } }; request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); request.open("POST", "saveDataURL.php", true); request.send("dataURL=" + canvas.toDataURL()); } 

To save the image on the server side, use the following PHP script:

 $dataURL = $_POST["dataURL"]; $encodedData = explode(',', $dataURL)[1]; $decodedData = base64_decode($encodedData); file_put_contents("images/faizan.png", $decodedData); echo "http://example.com/images/faizan.png"; 
+3
source

Got this job 100%! It was just necessary to debug this answer a little. Here's the working code:

JavaScript:

 var saveDataURL = function(canvas) { var dataURL = document.getElementById(canvas).toDataURL(); var params = "dataURL=" + encodeURIComponent(dataURL); var request = new XMLHttpRequest(); request.open("POST", "/save-data-url.php", true); request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); window.console.log(dataURL); request.onreadystatechange = function () { if (request.readyState === 4 && request.status === 200) { window.console.log(request.responseText); } }; request.send(params); } 

/scripts/save-data-url.php:

 <?php $dataURL = $_POST["dataURL"]; $encodedData = explode(',', $dataURL); $encodedData = $encodedData[1]; $decodedData = base64_decode($encodedData); file_put_contents("images/log.txt", $encodedData); file_put_contents("images/test.png", $decodedData); echo "http://www.mywebsite.com/images/test.png"; ?> 
+2
source

All Articles