svg to image on demand
Asked Answered
R

2

5

I have javascript code that generates svg image tags on the fly when a person lands on one of the pages. Im using the d3 library to help make the image. The only problem is that d3 is not fully IE compatible and I would want to generate a .png, jpg, gif or any other image file based on the svg file. Is there a known way to do this? The server side code is PHP based, and we use node.js, and render.js for a lot of the dynamic content.

Ricker answered 5/7, 2012 at 19:42 Comment(3)
I imagine you could also use Raphael to render the SVG to the browser - it works with IE too, apparently.Gayle
Thanks for the advice on Raphael. Sadly Raphael doesn't support some of the images that I want displayed the same way d3 does.Ricker
Ah, ok. I don't know if it might guide answers here, but it's worth a shot; would you edit your question and note what that kind of image is? It might prompt someone to a Eureka moment :)Gayle
S
5

I'm using ImageMagick to convert SVG images to PNG images. This works pretty well.

A quick example of how to do this:

exec('/usr/bin/convert /path/to/image.svg /path/to/output_image.png');

I'm using this with great success for processing QR codes made with libqrencode to different sizes and colors.

Subordinary answered 5/7, 2012 at 19:53 Comment(2)
FWIW, imagemagick uses librsvg which you could just use directly (rsvg-convert from librsvg). Moreover, the renderer is librsvg is only so-so so you might also try inkscape which can also convert to png from the command line.Monumental
Thanks. This helps out on a unrelated category with qr codes.Ricker
S
3

Firstly you need to use a DOM implementation on server side as you want to get svg which is rendered on client side.For this we use jsdom with node.js. Using this you can render D3 on server side and get svg on server then convert it to any format you like.

Here is the link on how to that.

Once you got SVG and PNG then by using modernizer.js

1)Check compatibility of browser using Modernizr.

2)Then load SVG or PNG basing upon on the compatibility.

Example (JS solution):

if (!Modernizr.svg) {
$("#logo").css("background-image", "url(fallback.png)");
}

Example (CSS solution):

.no-svg #logo { background-image: url(fallback.png); }
Selfmortification answered 13/12, 2012 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.