Created
April 16, 2011 14:07
-
-
Save jeffkreeftmeijer/923129 to your computer and use it in GitHub Desktop.
ChunkyPNG HSV
This file contains hidden or 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
require 'chunky_png' | |
module ChunkyPNG::Color | |
def h(value) | |
r,g,b = r(value).to_f / MAX, g(value).to_f / MAX, b(value).to_f / MAX | |
min, max = [r,g,b].minmax | |
return 0 if max == min | |
result = case max | |
when r then (g - b) / (max - min) + (g < b ? 6 : 0) | |
when g then (b - r) / (max - min) + 2 | |
when b then (r - g) / (max - min) + 4 | |
end | |
result * 60 | |
end | |
def s(value) | |
min, max = [r(value), g(value), b(value)].minmax.map { |value| value.to_f / MAX } | |
max == 0 ? 0 : (max - min) / max | |
end | |
def v(value) | |
[r(value), g(value), b(value)].max.to_f / MAX | |
end | |
def hsv(h, s, v) | |
h = h.to_f / 360 | |
i = (h * 6).floor | |
f = h * 6 - i | |
p = v * (1 - s) | |
q = v * (1 - f * s) | |
t = v * (1 - (1 - f) * s) | |
case i % 6 | |
when 0 then r, g, b = v, t, p | |
when 1 then r, g, b = q, v, p | |
when 2 then r, g, b = p, v, t | |
when 3 then r, g, b = p, q, v | |
when 4 then r, g, b = t, p, v | |
when 5 then r, g, b = v, p, q | |
end | |
rgb *[r,g,b].map {|value| (value * 255).round } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment