Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

javascript - 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 doing this?

I tried to create a canvas, load the png base64 and then used toDataURL('image/tiff') but after some research, I'd found that tiff is not supported as output of toDataURL().

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...