Ruby,RSVG和PNG流

我正在尝试在从SVG到PNG的rails应用程序中进行图像转换。 由于Heroku此时无法/想要升级IM,因此ImageMagick无法为我工作。 我正在测试一些在开发中使用RSVG2 / Cairo但遇到障碍的想法。

我可以轻松地将SVG转换并保存为PNG,如下所示:

#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) 

但这只能让我写出PNG文件。 在应用程序中,我需要能够动态生成这些内容,然后将它们作为数据发送到客户端浏览器。 我无法弄清楚如何做到这一点,或者即使它得到支持。 我知道我至少可以调用surface.data来获取原始数据,但我对图像格式知之甚少,不知道如何将其作为PNG。

谢谢

啊哈! 事后我非常接近并且非常明显。 只需使用StringIO对象调用surface.write_to_png函数即可。 这将填充字符串对象,然后您可以获取字节数。 这是我写的完成的svg_to_png函数,以及调用它的示例控制器。 希望这可以帮助其他人。

ImageConvertfunction:

  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 

测试控制器:

  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