Matt Scheurich
Matt Scheurich

Reputation: 1059

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.

Upvotes: 4

Views: 2885

Answers (3)

ecanals
ecanals

Reputation: 1

.to_blob and .from_blob both return an array of images. To get what you want, just call .first on the image array and you should have what you need.

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

Although the answers provided do work, in this case I find that deconstructing an array during variable assignment to be less legible than just calling .first on the generated array. Hope this helps!

Upvotes: 0

An RMagick User
An RMagick User

Reputation: 354

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

Upvotes: 2

Matt Scheurich
Matt Scheurich

Reputation: 1059

Well, after some experimenting I found that I can successfully use img.to_blob:

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

The key part is the img, data = Magick::Image... assignment.

Upvotes: 4

Related Questions