简体   繁体   中英

Download Google Chart as jpeg instead of png?

I am currently downloading Google Charts as png with the following code:

var imgUri = my_chart.getImageURI();
var url  = window.URL || window.webkitURL;
linkPNG = document.createElement("a");
linkPNG.href = imgUri;
linkPNG.download = title+".png";
link.click();

It works fine. Unfortunately, my users need a jpeg instead of a png, and my usual

var imgURL = my_chart.toDataURL( "image/jpeg" );

doesn't seem to work with Google Charts. How can I download the charts as .jpg instead of .png?

After spending some time looking through the obfuscated source of the visualization library, I have determined it would be easier to just recreate the image from the data URI rather than try to change the original export type. You can load the data URI with an image, draw it on a canvas, and convert it back to a data URI.

var img = new Image();
img.addEventListener('load', function() {
    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, img.width, img.height);
    ctx.drawImage(img, 0, 0);
    var link = document.createElement('a');
    link.href = canvas.toDataURL('image/jpeg');
    link.download = title + '.jpg';
    link.click();
});
img.src = my_chart.getImageURI();

Some error handling probably wouldn't be a bad idea either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM