1

I'm trying to code a javascript function that takes a Highcharts image, converts it to canvas, and downloads the file image locally (without going to the server).

My problem is specifically with IE. I tried using msSaveBlob with Blob and MSBlobBuilder; in the first case the file downloads however the content is incorrect (the image is damaged when opened).

Fist code uses Blob/msSaveBlob (see jsfiddle, run with IE):

var image = canvas.toDataURL("image/jpeg");     
if (navigator.msSaveBlob) {
    return navigator.msSaveBlob(new Blob([image],{type:"image/jpeg"}),"file23.jpeg");
} 

Second code uses MSBlobBuilder/msSaveBlob but doesn't generate a file (see jsfiddle, run with IE):

var image = canvas.toDataURL("image/jpeg"); 
if (window.MSBlobBuilder) {
    var bb = new MSBlobBuilder();
    bb.append(image);
    return navigator.msSaveBlob(bb, "file24.jpeg");
}

Any ideas how to make any of these work? Is there a preferred method? I understand this will work for IE10+ only.

ps0604
  • 1,227
  • 23
  • 133
  • 330
  • You jsFiddle links are 404. Also, how are you getting the canvas from Highcharts SVG? – Mark Oct 07 '14 at 15:19
  • Not sure what happened with jsFiddle, here you go again (canvas generated from highcharts and image downloaded with msSaveBlob) http://jsfiddle.net/ps0604/u7sxqu2e/1/ run with IE10 – ps0604 Oct 07 '14 at 15:53
  • small fix to the link above http://jsfiddle.net/ps0604/u7sxqu2e/2/ – ps0604 Oct 07 '14 at 16:26

1 Answers1

5

toDataURL produces a base64 string of the PNG. You need the raw data (or blob), though.

From this link:

By using canvas.toDataURL(), you preclude the possibility of easily using another application to view a saved drawing. Saving the drawing as a PNG file has the benefit of allowing a number of standard applications, including the browser, to display the drawing. By switching to canvas.msToBlob(), we can save the file directly to PNG...

So:

 canvg(canvas, svg);
 image = canvas.msToBlob();            
 if (navigator.msSaveBlob) {
     return navigator.msSaveBlob(new Blob([image],                       
                                    {type:"image/png"}),"file23.png");
 } 

Update fiddle.

EDITS

For a more universal way to convert base64 images to blobs see this answer here.

And an example of how to do it in this workflow:

var image = canvas.toDataURL( "image/jpeg" );
image = b64toBlob(image.replace("data:image/jpeg;base64,",""),"image/jpeg")

if (navigator.msSaveBlob) {
    return navigator.msSaveBlob(image,"file23.jpeg");
} 
Community
  • 1
  • 1
Mark
  • 106,305
  • 20
  • 172
  • 230
  • Thanks Mark. Is there a way to save a JPEG? msToBlob() seems to work only with PNG – ps0604 Oct 07 '14 at 17:32
  • @ps0604, see this: http://jsfiddle.net/u7sxqu2e/4/, it borrows from the awesome answer here: http://stackoverflow.com/a/16245768/16363 – Mark Oct 07 '14 at 19:25