Last active
June 5, 2017 17:09
-
-
Save jayliu50/bbf002f50c0deae063d126c97631fcc0 to your computer and use it in GitHub Desktop.
Make images contained within SVG files (exported through Sketch) not look washed out.
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
#!/usr/bin/env ruby | |
# usage: ruby image-in-svg.rb MY-IMAGE.svg | |
require 'nokogiri' | |
require 'mini_magick' | |
require 'base64' | |
## colorization | |
class String | |
# colorization | |
def colorize(color_code) | |
"\e[#{color_code}m#{self}\e[0m" | |
end | |
def red | |
colorize(31) | |
end | |
def green | |
colorize(32) | |
end | |
def yellow | |
colorize(33) | |
end | |
def blue | |
colorize(34) | |
end | |
def pink | |
colorize(35) | |
end | |
def light_blue | |
colorize(36) | |
end | |
end | |
HEADER = 'data:image/png;base64,' | |
def svg_process(svg) | |
svg = Nokogiri::XML svg | |
images = svg.css('svg image') | |
images.each do |svgImage| | |
base64img = (svgImage.get_attribute 'xlink:href')[(HEADER.length)..-1] | |
blob = Base64.decode64(base64img) | |
image = MiniMagick::Image.read blob | |
image.colorspace 'rgb' | |
base64img = Base64.encode64(image.to_blob) | |
svgImage.set_attribute 'xlink:href', "#{HEADER}#{base64img}" | |
end | |
svg.to_s | |
end | |
if (ARGV.length != 1) | |
puts "usage: ruby image-in-svg.rb MY-IMAGE.svg" | |
abort | |
end | |
raw_svg = File.open(ARGV[0], 'rb').read | |
File.write(ARGV[0], svg_process(raw_svg)) | |
puts "Processed your file #{ARGV[0].blue}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By changing the color space of the embedded images of the SVG from sRGB to RGB, we can avoid having the washed out look when loaded in Chrome.
Usage:
ruby image-in-svg.rb YOUR-IMAGE-NAME.svg
for specific fileruby image-in-svg.rb *.svg
for all the svgs in a directoryPrerequisites
gem install nokogiri
gem install mini_magick
gem install base64