将PNG Base-64字符串转换为TIFF Base-64字符串

MrC*_*ujo 2 javascript html5 base64 png tiff

我正在使用一个返回PNG编码的base64字符串的插件,我无法更改它,我必须使用它,但我真正需要的是tiff编码值(base-64).有办法做到这一点吗?

我试图创建一个画布,加载png base64然后使用toDataURL('image/tiff')但经过一些研究后,我发现tiff不支持输出toDataURL().

有什么建议?

小智 5

由于浏览器通常不支持TIFF作为目标文件格式,因此您必须通过使用类型化数组并根据文件规范构建文件结构来手动编码TIFF文件(请参阅此处的Photoshop说明).这是可行的:

  • 从canvas获取原始RGBA位图(请记住CORS很重要)
  • 使用带有DataView视图的类型化数组能够在未对齐位置写入各种数据
  • 构建文件头,定义最小TAG集并以您需要的方式编码RGBA数据(未压缩易于实现,或简单的RLE压缩).
  • 构造最终的文件缓冲区.从这里你有一个可以作为字节传输的ArrayBuffer,可选:
  • 使用ArrayBuffer和tiff mime-type转换为Blob.
  • 使用ArrayBuffer作为基础转换为Data-URI

更新 canvas-to-tiff可用于将画布保存为TIFF图像(免责声明:我是作者).

要使用canvas-to-tiff获取Data-URI,您只需执行以下操作:

CanvasToTIFF.toDataURL(canvasElement, function(url) {
   // url now contains the data-uri.
   window.location = url;    // download, does not work in IE; just to demo
});
Run Code Online (Sandbox Code Playgroud)

虽然,我建议使用toBlob(),或者如果你想给用户一个链接,toObjectURL()(而不是toDataURL).

使用Data-URI进行演示

var c = document.querySelector("canvas"),
    ctx = c.getContext("2d");

// draw some graphics
ctx.strokeStyle = "rgb(0, 135, 222)";
ctx.lineWidth = 30;
ctx.arc(200, 200, 170, 0, 2*Math.PI);
ctx.stroke();

// Covert to TIFF using Data-URI (slower, larger size)
CanvasToTIFF.toDataURL(c, function(url) {
  var a = document.querySelector("a");
  a.href = url;
  a.innerHTML = "Right-click this link, select Save As to save the TIFF";
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.rawgit.com/epistemex/canvas-to-tiff/master/canvastotiff.min.js">
</script>
<a href=""></a><br>
<canvas width=400 height=400></canvas>
Run Code Online (Sandbox Code Playgroud)

使用Object-URL进行演示

var c = document.querySelector("canvas"),
    ctx = c.getContext("2d");

// draw some graphics
ctx.strokeStyle = "rgb(0, 135, 222)";
ctx.lineWidth = 30;
ctx.arc(200, 200, 170, 0, 2*Math.PI);
ctx.stroke();

// Covert to TIFF using Object-URL (faster, smaller size)
CanvasToTIFF.toObjectURL(c, function(url) {
  var a = document.querySelector("a");
  a.href = url;
  a.innerHTML = "Right-click this link, select Save As to save the TIFF";
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.rawgit.com/epistemex/canvas-to-tiff/master/canvastotiff.min.js">
</script>
<a href=""></a><br>
<canvas width=400 height=400></canvas>
Run Code Online (Sandbox Code Playgroud)