重命名从HTML5画布创建的图像 [英] Renaming an image created from an HTML5 canvas
问题描述
我制作了一个简单的画布并将其保存为图像。我在这段代码的帮助下做到了这一点:
I have made a simple canvas and save it as an image. I have done this with the help of this code:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
并弹出创建的图片:
document.write('<img src="'+img+'"/>');
但它的名字总是很奇怪。我想重命名图像名称,如 faizan.jpg
等。我该怎么做?
But its name is always a weird one. I want to rename the image name like faizan.jpg
etc. How can I do this?
推荐答案
简单地说,你不能。当您在HTMLCanvasElement上调用toDataURL方法时,它会生成图像的字符串表示形式作为数据URL。因此,如果您尝试保存图像,浏览器会为其提供默认文件名(例如,如果数据URL是png文件,Opera会将其保存为default.png)。
To put it simply, you can't. When you call the toDataURL method on an HTMLCanvasElement it generates a string representation of the image as a Data URL. Thus if you try to save the image, the browser gives it a default filename (e.g. Opera saves it as default.png if the Data URL was a png file).
存在许多变通方法。最简单的方法是对服务器进行AJAX调用,在服务器端保存图像并返回保存图像的URL,然后可以在客户端访问和保存:
Many workarounds exist. The simplest one is to make an AJAX call to a server, save the image on the server-side and return the URL of the saved image which can then be accessed 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());
}
要在服务器端保存图像,请使用以下PHP脚本:
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";
这篇关于重命名从HTML5画布创建的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!