Search code examples
rubysvgpngrmagick

Converting SVG to PNG with RMagick in memory


I'm having a frustrating time converting an SVG string into a PNG string using RMagick:

def convert_svg_to_png(str)
  img = Magick::Image.from_blob(str) {
    self.format = 'SVG'
    self.background_color = 'transparent'
  }
  img.to_blob {
    self.format = 'PNG'
  }
end

I get the error: 'convert_svg_to_png': undefined method 'to_blob' for [ SVG 100x10 100x10+0+0 DirectClass 16-bit 167b]:Array)

My only thought is that the img instance after from_blob is not a Magick::Image instance (since the error says it's an [ SVG ... :Array]). I haven't found anything online that concretely answers converting an image from SVG to PNG in memory. Lots of mentions of to_blob but no workable examples.


Solution

  • The RMagick doc for from_blob says that from_blob returns an array of images, so my guess is that this should work:

    arr = Magick::Image.from_blob(str)
    str = arr[0].to_blob