Ruby, RSVG and PNG streams

荒凉一梦 提交于 2019-12-03 13:49:18

问题


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 testing out some ideas of using RSVG2 / Cairo in dev but running into a roadblock.

I can easily convert and save the SVG to PNG like this:

#svg_test.rb
require 'debugger'
require 'rubygems'
require 'rsvg2'

SRC = 'test.svg'
DST = 'test.png'

svg = RSVG::Handle.new_from_file(SRC)
surface = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, 800, 800)
context = Cairo::Context.new(surface)
context.render_rsvg_handle(svg)
surface.write_to_png(DST)

But this only lets me write PNG files out. In the app, I need to be able to generate these on the fly, then send them down to the client browser as data. And I can't figure out how to do this, or even if its supported. I know I can call surface.data to get the raw data at least, but I don't know enough about image formats to know how to get this as a PNG.

Thanks


回答1:


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


来源:https://stackoverflow.com/questions/11436873/ruby-rsvg-and-png-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!