Ruby, RSVG and PNG streams

后端 未结 1 1624
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 13:45

I\'m trying to do an image conversion in a rails app from SVG to PNG. ImageMagick didn\'t work out for me, due to Heroku not able / wanting to upgrade IM at this time. I\'m te

相关标签:
1条回答
  • 2021-02-06 14:09

    Ah ha! I was so close and its pretty obvious in hindsight. Simply call the surface.write_to_png function with a StringIO object. This fills the string object, which you can then get the bytes for. Here's the finished svg_to_png function I wrote, along with a sample controller that calls it. Hope this helps someone else somewhere.

    ImageConvert function:

      def self.svg_to_png(svg)
        svg = RSVG::Handle.new_from_data(svg)
        surface = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, 800, 800)
        context = Cairo::Context.new(surface)
        context.render_rsvg_handle(svg)
        b = StringIO.new
        surface.write_to_png(b)
        return b.string
      end
    

    Test controller:

      def svg_img
        path = File.expand_path('../../../public/images/test.svg', __FILE__)
        f = File.open(path, 'r')
        t = ImageConvert.svg_to_png(f.read)
        send_data(t , :filename => 'test.png', :type=>'image/png')
      end
    
    0 讨论(0)
提交回复
热议问题