Ruby,RSVG和PNG流 [英] Ruby, RSVG and PNG streams
问题描述
我正在尝试在Rails应用中将图像从SVG转换为PNG.由于Heroku目前无法/想要升级IM,因此ImageMagick不适用于我.我正在测试在开发人员中使用RSVG2/Cairo的一些想法,但遇到了障碍.
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.
我可以像这样轻松地将SVG转换并保存为PNG:
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)
但这只能让我写出PNG文件.在应用程序中,我需要能够即时生成这些内容,然后将它们作为数据发送到客户端浏览器.而且我不知道如何做到这一点,即使它支持.我知道我至少可以调用surface.data来获取原始数据,但是我对图像格式的了解还不足以知道如何将其作为PNG来获取.
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.
谢谢
推荐答案
啊哈!我是如此亲密,事后看来很明显.只需使用StringIO对象调用surface.write_to_png函数.这将填充字符串对象,然后您可以获取其字节.这是我编写的完成的svg_to_png函数,以及调用它的示例控制器.希望这可以帮助其他人.
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函数:
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
测试控制器:
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和PNG流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!