Reputation: 954
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?
Upvotes: 0
Views: 954
Reputation: 2794
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.
Upvotes: 1