Base64映像下载:损坏的文件
Base64 Image Download: Corrupted File
我有一个脚本,可以将画布元素转换为base64编码的图像,将其设置为链接的href
,并允许用户将其下载为jpeg。I
在开发工具中,我可以打开数据URL并查看图像,并且我已经验证了链接的href
是否已适当更新。但是,无法查看下载的文件。试图在PhotoShop中打开它显示以下错误:
无法完成您的请求,因为JPEG标记段长度太短(文件可能被截断或不完整)。
是什么原因造成的?
以下是点击时设置href
值的函数:
$(a).click(function() {
var e = r.toDataURL("image/jpeg");
console.log(e); //Verify base64 encoded image which works correctly
a.href = e;
});
以下内容适用于我。我怀疑您的问题可能与浏览器兼容性有关。
<h1>Copy graphic using toDataURL</h1>
<div>
<button id="copy">Copy canvas image to image element</button> <br />
<canvas id="MyCanvas" width="400" height="400" >This browser or document mode doesn't support canvas</canvas>
<img id="MyPix" src="" width="400" height="400" />
<a id="myAnchor" href="#" download>Some Link that should download whatever it's pointing to</a>
</div>
<script>
// Create some graphics on the canvas.
var canvas = document.getElementById("MyCanvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "white";
ctx.beginPath();
ctx.rect(5, 5, 300, 250);
ctx.fill();
ctx.stroke();
ctx.arc(150, 150, 100, 0, Math.PI, false);
ctx.stroke();
}
// catch the click from the button and copy the graphic
document.getElementById("copy").addEventListener("click", function () {
var canvas1 = document.getElementById("MyCanvas");
var anchor = document.getElementById("myAnchor");
if (canvas1.getContext) {
var ctx = canvas1.getContext("2d"); // Get the context for the canvas.
var myImage = canvas1.toDataURL("image/jpeg"); // Get the data as an image.
}
var imageElement = document.getElementById("MyPix"); // Get the img object.
imageElement.src = myImage; // Set the src to data from the canvas.
anchor.href = myImage;
}, false);
</script>
我认为在单击事件中设置Href是个坏主意。请尝试在单击之前进行设置。请参阅此代码:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<a id="link" href="#">Download</a>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(150, 150);
ctx.arc (100,75,50,0,2*Math.PI);
context.closePath();
context.lineWidth = 3;
context.strokeStyle = '#444';
context.stroke();
var dataURL = canvas.toDataURL();
document.getElementById("link").href = dataURL;
</script>
</body>
</html>
它会画一个圆圈,然后直接设置链接的HREF。这会很好用的。
相关文章:
- 将 MVC 3 应用程序部署到 URL 文件夹已损坏 JavaScript 和内容路径
- 节点 js 流星 js 图像文件上传图像损坏
- 如果数据的格式略有损坏,是否仍然可以确定其文件类型
- 图像文件因websocket文件传输而损坏
- AJAX响应提供了一个损坏的压缩(.tgz)文件
- 存储/检索 html 5 文件对象,用于恢复损坏的文件上传
- Javascript Blob 锚标记下载生成损坏的文件
- jsPDF 不完整或损坏的 PNG 文件
- Base64 - 文件已损坏
- 如何使用javascript和jquery-file-upload检测损坏的非常大的图像文件
- 使用nodeJS上传时文件损坏
- 如何在 Node.js 中检测损坏的图像文件
- Base64映像下载:损坏的文件
- MVC ActionResult调用文件下载时mouseup上的图像损坏
- Ajax responseText和echo已损坏,返回头文件内容
- 上传到nodejs时损坏的文件/图像
- 通过PHP下载时文件损坏的原因
- Javascript文件自动损坏
- 导出html到Excel:当尝试打开文件时,它会提示文件损坏
- 使用angular $http下载时文件损坏