-->

红宝石,RSVG和PNG流(Ruby, RSVG and PNG streams)

2019-07-30 09:07发布

我试图做一个图像转换的Rails应用程序从SVG至PNG。 ImageMagick的并没有为我工作了,由于Heroku的不能/不想在这个时候升级IM。 我测试了在开发中使用RSVG2 /开罗但运行到一个路障的一些想法。

我可以很容易地转换和保存这样的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。

谢谢

Answer 1:

啊哈! 我是如此接近其在事后很明显的。 只需拨打一个StringIO对象的surface.write_to_png功能。 这填补了字符串对象,然后你就可以得到的字节数。 下面是我写的,与调用它的样本控制器一起完成的svg_to_png功能。 希望这可以帮助别人的地方。

ImageConvert功能:

  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


文章来源: Ruby, RSVG and PNG streams