Last active
March 14, 2024 07:52
-
-
Save syon/40516d53932f5757d8a8 to your computer and use it in GitHub Desktop.
SVG-to-PNG Converter using Ruby-GNOME2/RSVG on Sinatra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source "https://rubygems.org" | |
gem "sinatra" | |
gem "haml" | |
gem "rsvg2" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!!!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