Data, Maps, Usability, and Performance

Save SVG as an Image

Last updated on March 27, 2015 in Development

Convert SVG to Image

SVG is awesome but sometimes you want to convert it into an image format like a JPG or PNG. If you created some chart or graph with D3.js, you might want to offer the option of saving that graph in an image format. Looking around, I landed on this Save SVG as PNG article and while it provides a good solutions to the problem, I wanted to expand on it and provide some other options. First of all, I want to go through an example where you are creating something in D3 and then want to make this conversion using a button and a JavaScript function. I think you could provide 3 types of image files: an SVG converted to a dataurl and inserted into an image tag (this is still technically SVG), a SVG converted into a PNG using HTML5 CANVAS and inserting that base64 data into an IMG tag, and finally, converting the SVG into a PNG binary data and loading that into a blob url so that you can provide an actual filename inside of an IMG tag.

Let’s start with a simple D3 example. I have slightly modified this example here by placing the SVG contents into a div instead of body and I added a “save as image” button and function. Here is a gist of the function:

So, we grab the D3.js generated SVG, convert it into a base64 dataurl, and stick it into an IMG tag. Since this is still SVG, lets load it into an an actual image and load that image into a CANVAS object. At this point we can grab the PNG dataurl from CANVAS and insert that into an IMG tag on the page. Now, we have an actual PNG image with base64 encoded image data in the source. Using the HTML5 link download attribute we can force the browser to download that image programatically. Here is the result and our new function looks like this:

Now, this is pretty cool, especially that you can programmatically download the image file but how about actually creating an image file on the client side? We can use a blob to store the image data and then drop it into a blob url. I have covered Blobs before in my Drag and Drop Image Upload to Imgur example and Making Video Screenshots with HTML5 demo but that code leveraged the HTML FileReader functionality while here we can just convert image data into a binary format with atob and DataView. Here is the final result and our canvas data to binary image function:

Finally, lets finish this of with a drag and drop SVG to PNG image converter. You can check out the source to see how that works.


SVG Crowbar – Chrome-specific bookmarklet that extracts SVG nodes and accompanying styles from an HTML document and downloads them as an SVG file

Tags: , , ,

Facebook Twitter Hacker News Reddit More...