Skip to content

Instantly share code, notes, and snippets.

@jayliu50
Last active June 5, 2017 17:09
Show Gist options
  • Save jayliu50/bbf002f50c0deae063d126c97631fcc0 to your computer and use it in GitHub Desktop.
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.
#!/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}"
@jayliu50
Copy link
Author

jayliu50 commented Jun 5, 2017

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 file
ruby image-in-svg.rb *.svg for all the svgs in a directory

Prerequisites

  • Install ImageMagick
  • Possibly having to run the following commands:
    • gem install nokogiri
    • gem install mini_magick
    • gem install base64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment