脚本.jpg图像保存到磁盘,但图像在上传到 3p 托管站点时转换为.png



手头的任务是在 1600 x 1600 的白色背景上将.jpg图像(以前上传到图像托管站点)居中,并包含一个链接,将生成的图像直接下载到我的 PC。下面的代码完成了任务。单击下载链接后,.jpg将下载到我的PC上,其中包含必要的规格。但是,当此新.jpg图像上传到图像托管站点时,生成的上传是一个.png文件。白色背景消失。

一些注意事项:用油漆打开图像并将其另存为.jpeg文件,并显示一条通知,指出任何透明度都将丢失。如果我要继续,则图像将以所需的规格保存,并将作为.jpg上传到图像托管站点。我怀疑我创建了一个具有透明背景的图像(不是所需的白色),当删除时,透明画布会变成白色。此外,无论我使用哪种 3p 主机,生成的.jpg映像都会更改为 .png。

<!DOCTYPE html>
<html>
<body>
<left>
<a id="myAnchor" download="image.jpg"><b><u>Download</u></b></a>
</left>
<img crossOrigin="anonymous" src="http://i1213.photobucket.com/albums/cc475/kmkcorp/TigsMoney1_zpst9wv6cdb.jpg" id="img" style="display:none" alt="picture"/></image>
<canvas id="canvas" width="1600" height="1600" style="border:0px;"></canvas>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("img");
ctx.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2);
ctx.canvas.toBlob(function(blob){
myAnchor.href = URL.createObjectURL(blob);});
var revokeURL=function(){
requestAnimationFrame(function(){
URL.revokeObjectURL(this.href);
this.href=null;});
this.removeEventListener('click', revokeURL);};
myanchor.addEventListener('click', revokeURL);};
img.src="http://i1213.photobucket.com/albums/cc475/kmkcorp/TigsMoney1_zpst9wv6cdb.jpg";
</script>
</body>
</html>

canvas.toBlob()type参数设置为"image/jpeg"

要将<canvas>的背景填充为特定颜色,您可以使用.fillStyle.fillRect().

也应该canvas.toBlob()ctx.canvas.toBlob();myanchor.addEventListener('click', revokeURL)应该是myAnchor.addEventListener('click', revokeURL)的;并且this在传递给requestAnimationFrame的函数中window。如果下载提议预计仅出现一次,则可以删除hrefdownload属性。

<!DOCTYPE html>
<html>
<body>
<a id="myAnchor" download="image.jpg"><b><u>Download</u></b></a>
<img crossOrigin="anonymous" src="http://i1213.photobucket.com/albums/cc475/kmkcorp/TigsMoney1_zpst9wv6cdb.jpg" id="img" style="display:none" alt="picture" />
<canvas id="canvas" width="1600" height="1600" style="border:0px;"></canvas>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var img = document.getElementById("img");
ctx.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2);
canvas.toBlob(function(blob) {
myAnchor.href = URL.createObjectURL(blob);
}, "image/jpeg");
var revokeURL = function() {
requestAnimationFrame(function() {
URL.revokeObjectURL(this.href);
myAnchor.removeAttribute("href");
myAnchor.removeAttribute("download");
});
this.removeEventListener('click', revokeURL);
};
myAnchor.addEventListener('click', revokeURL);
img.src = "http://i1213.photobucket.com/albums/cc475/kmkcorp/TigsMoney1_zpst9wv6cdb.jpg";
};
</script>
</body>
</html>

最新更新