Skip to content

Instantly share code, notes, and snippets.

@cabb
Forked from botanicus/svg_processing.rb
Created May 10, 2022 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cabb/2a0f49b9a4c44e074a866e17a2274491 to your computer and use it in GitHub Desktop.
Save cabb/2a0f49b9a4c44e074a866e17a2274491 to your computer and use it in GitHub Desktop.
Change colours of a SVG image with Nokogiri.
#!/usr/bin/env ruby
# encoding: utf-8
require "nokogiri"
require "fileutils"
# setup
required_colors = ["ff000", "006600", "003399"]
# main
Dir["*.svg"].each do |path|
original = File.read(path)
basename = File.basename(path).split(".").first
document = Nokogiri::XML.parse(original)
begin
FileUtils.mkdir(basename)
rescue Errno::EEXIST
end
Dir.chdir(basename) do
required_colors.each do |color|
File.open("#{color}.svg", "w") do |file|
current = document.dup
# current.xpath("//*[@fill]").set(:fill, "##{color}")
# current.xpath("/svg/g/path[not(@fill)]").set(:fill, "##{color}") # doesn't work for some reason
current.css("path:not([fill])").set(:fill, "##{color}")
file.puts(current)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment