7

After having spent two days attempting to rasterize jpeg's from SVG strings using ImageMagick I have finally given up.

Although I managed to get the actual conversion working fine it seems Imagemagick cannot properly convert the transform/rotate features correctly when rendering the image, leaving the output different to the original SVG.

Having researched further it appears that this is a known issue and that 'Inkscape' is the best method to use for converting SVG into jpeg/png in PHP.

The problem is that my SVG data is sent to my PHP script via JSON. How do I get a blob or string into the Inkscape command line in order to have it converted?

Many thanks for any suggestions.

gordyr
  • 6,078
  • 14
  • 65
  • 123

2 Answers2

3

If you have an SVG string, and you're sending it from the browser to the server via AJAX, you'll need to write it to a temp file, so it can be referenced from the Inkscape command line. You can't render to JPEG using the Inkscape command line, but you can render to PNG easily, and if you really need a different format, of course you can convert using ImageMagick subsequently.

You'll need something like:

/path/to/inkscape \
    --without-gui \
    --export-png=/path/to/output.png \
    /tmp/file/input.svg

If you are accepting full/partial SVG input from the user, bear in mind there are a good number of security issues you need to bear in mind. Happy to expand on this if required.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Of course, I cant believe I didn't think of that. The SVG input is all generated client side within the app (dragging and transforming objects/images etc) so the user never actually gets to input any SVG code themselves. That said this still leaves several security holes which I am well aware of. Thanks for the quick and precise answer! – gordyr May 01 '12 at 16:40
  • No probs. So long as you know about the security holes - I am working on a application in which users upload an SVG doc, and I'm finding interesting "features" frequently! – halfer May 01 '12 at 16:42
  • I can only imagine what your up against with that one! ouch!... Thanks again :-) – gordyr May 01 '12 at 16:43
3

You could pass your SVG string to inkscape using stdin, but the code is less portable.

// Open Inkscape process
$process = proc_open(
    '/path/to/inkscape -z -f /dev/fd/0 -e /path/to/output' 
    array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')), 
    $pipes
);

// Write svg to stdin
fwrite($pipes[0], $svg);

// Close process
foreach ($pipes as $pipe) fclose($pipe);
proc_close($process);
Chris
  • 208
  • 1
  • 5