Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert SVG string to file or PNG in Ruby?

I'm sending a SVG string from browser (Javascript) to a server that is running Rails (Ruby). I want to convert this string to a PNG with transparency or, at least, a SVG file so I can convert it later

Any ideas? I installed RMagick but I'm still not sure how to create the file from the string.

Any other solution to achieve this?

The idea is to create simple "logos" dynamically

like image 806
Victor Ferreira Avatar asked Jun 02 '15 17:06

Victor Ferreira


People also ask

How do I save a SVG file as a PNG in Chrome?

svg file, right click on it and click on the context menu item 'Save SVG as PNG. Lets you click on the extension icon or right click on an . svg file and choose Save SVG as PNG. You will be able to specify the desired width of the rendered PNG image.


1 Answers

With RMagick, just read the string into an image instance with Image.from_blob + defining the SVG format

require "RMagick"

svg_string='
<svg xmlns="http://www.w3.org/2000/svg"  width="120" height="120" viewPort="0 0 120 120" version="1.1">
  <rect width="150" height="150" fill="rgb(0, 255, 0)" stroke-width="1" stroke="rgb(0, 0, 0)" />
  <line x1="20" y1="100" x2="100" y2="20" stroke="black" stroke-width="2"/>
</svg>'

img = Magick::Image.from_blob(svg_string) {
  self.format = 'SVG'
  self.background_color = 'transparent'
}
img.write "example_out.png"

How to convert SVG string to file or PNG in Ruby

Edit

If the string is just a SVG path, there's Magick::Draw.path to "rebuild" vector graphics. Doc & examples here.

like image 171
emcconville Avatar answered Sep 19 '22 05:09

emcconville