Skip to content Skip to sidebar Skip to footer

Convert PNG Base-64 String To TIFF Base-64 String

I'm using a plugin that returns a PNG encoded base64 string, I cannot change it, I must work with it, but what I really need is the tiff encoded value (base-64). Is there a way of

Solution 1:

As TIFF is not generally supported as target file-format in the browser, you will have to manually encode the TIFF file by building up the file-structure using typed arrays and in accordance with the file specifications (see Photoshop notes here). It's doable:

  • Get the raw RGBA bitmap from canvas (remember that CORS matters)
  • Use typed arrays with DataView view to be able to write various data at unaligned positions
  • Build up file header, define minimum set of TAGS and encode the RGBA data in the way you need (uncompressed is simple to implement, or a simple RLE compression).
  • Construct the final file buffer. From here you have an ArrayBuffer you can transfer as bytes, optionally:
  • Convert to Blob with ArrayBuffer and tiff mime-type.
  • Convert to Data-URI using ArrayBuffer as basis

Update canvas-to-tiff can be used to save canvas as TIFF images (disclaimer: I'm the author).

To get an Data-URI using canvas-to-tiff you can simply do:

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

Although, I would recommend using toBlob(), or if you want to give the user a link, toObjectURL() (instead of toDataURL).

Demo using 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";
})
<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>

Demo using 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";
})
<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>

Post a Comment for "Convert PNG Base-64 String To TIFF Base-64 String"