Rubies, RSVG and PNG

I am trying to convert an image in a rails application from SVG to PNG. ImageMagick didnโ€™t work for me, because Heroku was unable / unable to update IM at this time. I am testing some ideas for using RSVG2 / Cairo in dev, but have run into an obstacle.

I can easily convert and save SVG to PNG as follows:

#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 it only allows me to write PNG files. In the application, I need to be able to generate them on the fly, and then send them to the client browser as data. And I canโ€™t understand how to do this, or even if it is supported. I know that I can call surface.data to get the raw data, but I don't know enough about image formats to know how to get this as PNG.

thanks

+4
ruby-on-rails png
source share
1 answer

Yeah! I was so close and pretty obvious. Just call the surface.write_to_png function with a StringIO object. This fills the string object you can get for bytes. The svg_to_png function that I wrote along with the sample controller that calls it is finished here. Hope this helps someone else.

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 

Testing 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 
+7
source share

All Articles