Skip to content

Instantly share code, notes, and snippets.

@syon
Last active March 14, 2024 07:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save syon/40516d53932f5757d8a8 to your computer and use it in GitHub Desktop.
Save syon/40516d53932f5757d8a8 to your computer and use it in GitHub Desktop.
SVG-to-PNG Converter using Ruby-GNOME2/RSVG on Sinatra
# coding: utf-8
require 'sinatra'
require 'rsvg2'
require 'haml'
get '/' do
haml :index
end
post '/result' do
if params[:file]
svg_data = params[:file][:tempfile].read
png_data = ImageConvert.svg_to_png(svg_data, params[:width].to_i, params[:height].to_i)
else
end
content_type 'png'
png_data
end
class ImageConvert
def self.svg_to_png(svg, width, height)
svg = RSVG::Handle.new_from_data(svg)
width = width ||=500
height = height ||=500
surface = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, width, height)
context = Cairo::Context.new(surface)
context.render_rsvg_handle(svg)
b = StringIO.new
surface.write_to_png(b)
return b.string
end
end
source "https://rubygems.org"
gem "sinatra"
gem "haml"
gem "rsvg2"
!!!html5
%html
%head
%meta{:charset => "UTF-8"}
%title SVG to PNG
%body
%h1 SVG to PNG
%form{:action => "./result", :method => "post", :enctype => "multipart/form-data"}
%ul
%li
%input{:type => "file", :name => "file"}
%li
%input{:type => "number", :name => "width", :value => "500"}
%li
%input{:type => "number", :name => "height", :value => "500"}
%input{:type => "submit", :name => "submit"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment