Skip to content

Instantly share code, notes, and snippets.

@ryan5500
Last active August 29, 2015 14:06
Show Gist options
  • Save ryan5500/7525218f5a8522645467 to your computer and use it in GitHub Desktop.
Save ryan5500/7525218f5a8522645467 to your computer and use it in GitHub Desktop.
Getting ColorScheme From Stylesheet
#!/usr/bin/env ruby
#
## How To Use
#
# $ ./extract_colors_from_css.rb style.css > out.html
# $ open out.html
#
#
# CSSから色の記述だけ抜き出す
#
def extract_colors css_lines
colors = []
css_lines.each do |line|
matches = line.match(/#[0-9A-F]{6}/i)
colors << matches[0] if !matches.nil? && !colors.include?(matches[0])
end
colors
end
#
# 色差を計算する
#
def calc_color_diff color1, color2
# hashを除く
color1 = color1[1..color1.length]
color2 = color2[1..color2.length]
# r, g, bの成分に分ける
c1_r = color1[0..1].hex
c1_g = color1[2..3].hex
c1_b = color1[4..5].hex
c2_r = color2[0..1].hex
c2_g = color2[2..3].hex
c2_b = color2[4..5].hex
([c1_r, c2_r].max - [c1_r, c2_r].min) +
([c1_g, c2_g].max - [c1_g, c2_g].min) +
([c1_b, c2_b].max - [c1_b, c2_b].min)
end
#
# 灰色っぽい色か否かを判定する
#
def is_grayish_color? color
# hashを除く
color = color[1..color.length]
r = color[0..1].hex
g = color[2..3].hex
b = color[4..5].hex
((r - g).abs < 20 && (g - b).abs < 20 && (r - b).abs < 20)
end
#
# CSSから抜き出した色を表示するために、
# colorsの各色を持つdivが並んだhtmlを出力する
#
def make_html colors
html =<<EOF
<html>
<body>
EOF
if colors[0].class != Array
colors = [colors]
end
colors.each do |cs|
html += "<div style='float:left; width: 100px;'>"
cs.each do |color|
html += "<div style='width:100px; height:100px; background-color: #{color};'></div>"
end
html += "</div>"
end
html += '</body></html>'
html
end
if __FILE__ == $0
filename = ARGV[0]
unless filename
puts 'filename not found'
exit 1
end
lines = []
open(filename).each_line {|line| lines << line }
colors = extract_colors lines
colors = colors.select {|c| !is_grayish_color?(c) }
new_colors = []
colors.each do |c|
cs = [c]
colors.each do |color|
next if c == color
diff = calc_color_diff c, color
cs << color if diff > 255 # 十分な色差があるものだけを選抜する
end
new_colors << cs
end
puts make_html(new_colors)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment