Skip to content

Instantly share code, notes, and snippets.

@wilkie
Created October 26, 2014 02:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilkie/d0c5e0054e11874c6f7d to your computer and use it in GitHub Desktop.
Save wilkie/d0c5e0054e11874c6f7d to your computer and use it in GitHub Desktop.
This shows you how to handle simple, dynamic colored versions of svg files in ruby + sinatra.

This is an example of how to present a route in Sinatra that returns a colored version of an existing svg. This assumes the first line is the line, which is what inkscape produces. Just drop in any svg, and it will give you one where it is colored in with the given color.

/dynamic/foo.svg returns the normal image.

/dynamic/foo.svg?color=red gives you a red image.

/dynamic/foo.svg?hue=150&sat=50&light=50 gives you a slightly green version of the image.

/dynamic/foo.svg?hex=fff gives a white version of the image.

class Application < Sinatra::Base
# Allow dynamic colors for any arbitrary svg files
# XXX: assumes <?xml ... ?> line is the first line
get '/dynamic/:name.svg' do
content_type = "image/svg+xml"
if params["hex"]
params["color"] = "##{params["hex"]}"
elsif params["hue"] and params["sat"] and params["light"]
params["color"] = "hsl(#{params["hue"]}, #{params["sat"]}%, #{params["light"]}%)"
end
if params["color"]
require 'base64'
headers 'Content-Type' => "image/svg+xml"
css = "path, rect { fill: #{params["color"]} !important; stroke: #{params["color"]} !important }"
embed = Base64.encode64(css)
stream do |out|
File.open("public/images/#{params[:name]}.svg") do |f|
out << f.readline
out << "<?xml-stylesheet type=\"text/css\" href=\"data:text/css;charset=utf-8;base64,#{embed}\" ?>"
out << f.read
end
end
else
send_file "public/images/#{params[:name]}.svg"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment