Skip to content

Instantly share code, notes, and snippets.

@makevoid
Created October 19, 2012 13:43
Show Gist options
  • Select an option

  • Save makevoid/3918299 to your computer and use it in GitHub Desktop.

Select an option

Save makevoid/3918299 to your computer and use it in GitHub Desktop.
Convert HSV colors to RGB and back (with specs)
# http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically
def hsv_to_rgb(h, s, v)
h, s, v = h.to_f/360, s.to_f/100, v.to_f/100
h_i = (h*6).to_i
f = h*6 - h_i
p = v * (1 - s)
q = v * (1 - f*s)
t = v * (1 - (1 - f) * s)
r, g, b = v, t, p if h_i==0
r, g, b = q, v, p if h_i==1
r, g, b = p, v, t if h_i==2
r, g, b = p, q, v if h_i==3
r, g, b = t, p, v if h_i==4
r, g, b = v, p, q if h_i==5
[(r*255).to_i, (g*255).to_i, (b*255).to_i]
end
# http://ntlk.net/2011/11/21/convert-rgb-to-hsb-hsv-in-ruby/
def rgb_to_hsv(r, g, b)
r = r / 255.0
g = g / 255.0
b = b / 255.0
max = [r, g, b].max
min = [r, g, b].min
delta = max - min
v = max * 100
if (max != 0.0)
s = delta / max *100
else
s = 0.0
end
if (s == 0.0)
h = 0.0
else
if (r == max)
h = (g - b) / delta
elsif (g == max)
h = 2 + (b - r) / delta
elsif (b == max)
h = 4 + (r - g) / delta
end
h *= 60.0
if (h < 0)
h += 360.0
end
end
[h, s, v]
end
COLORS = [
{ rgb: [ 0, 0, 0], hsv: [ 0, 0, 0] }, # black
{ rgb: [255, 255, 255], hsv: [ 0, 0, 100] }, # white
{ rgb: [255, 0, 0], hsv: [ 0, 100, 100] }, # red
{ rgb: [ 0, 255, 0], hsv: [120, 100, 100] }, # green
{ rgb: [ 0, 0, 255], hsv: [240, 100, 100] }, # blue
{ rgb: [255, 255, 0], hsv: [ 60, 100, 100] }, # yellow
{ rgb: [ 0, 255, 255], hsv: [180, 100, 100] }, # cyan
{ rgb: [255, 0, 255], hsv: [300, 100, 100] }, # magenta
# non-standards
{ rgb: [127, 127, 127], hsv: [ 0, 0, 50] }, # grey
{ rgb: [127, 74, 0], hsv: [ 35, 100, 50] }, # brown
{ rgb: [255, 153, 255], hsv: [300, 40, 100] }, # pink
{ rgb: [255, 148, 0], hsv: [ 35, 100, 100] }, # orange
]
describe "Color" do
COLORS.each do |color|
it "converts rgb to hsv (with approximation)" do
h, s, v = rgb_to_hsv(*color[:rgb])
hb, sb, vb = color[:hsv]
h.should < hb+1
h.should > hb-1
s.should < sb+1
s.should > sb-1
v.should < vb+1
v.should > vb-1
end
it "converts hsv to rgb" do
hsv_to_rgb(*color[:hsv]).should == color[:rgb]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment