Class: Color::RGB
- Inherits:
-
Data
- Object
- Data
- Color::RGB
- Includes:
- Color
- Defined in:
- lib/color/rgb.rb,
lib/color.rb,
lib/color/rgb/colors.rb
Overview
The RGB color model is an additive color model where the primary colors (red, green, and blue) of light are added to produce millions of colors. RGB rendering is device-dependent and without color management, the same “red” color will render differently.
This class does not implement color management and is not RGB colorspace aware; that is, unless otherwise noted, it does not assume that the RGB represented is sRGB or Adobe RGB (opRGB).
RGB colors are immutable Data class instances. Array deconstruction is ‘[red, green, blue]` and hash deconstruction is `red:, g:, green:, b:, blue`. See #r, #red, #g, #green, #b, #blue.
Defined Under Namespace
Modules: Metallic
Constant Summary collapse
- Black000 =
:nodoc:
new(r: 0x00, g: 0x00, b: 0x00)
- WhiteFFF =
:nodoc:
new(r: 0xff, g: 0xff, b: 0xff)
Constants included from Color
Instance Attribute Summary collapse
-
#b ⇒ Object
readonly
Returns the value of attribute b.
-
#g ⇒ Object
readonly
Returns the value of attribute g.
-
#names ⇒ Object
readonly
Returns the value of attribute names.
-
#r ⇒ Object
readonly
Returns the value of attribute r.
Class Method Summary collapse
- .__create_named_colors(mod, *colors) ⇒ Object
-
.by_css(name_or_hex, &block) ⇒ Object
Return a color as identified by the color name, or by hex.
-
.by_hex(hex) ⇒ Object
Find or create a color by an HTML hex code.
-
.by_name(name, &block) ⇒ Object
Return a color as identified by the color name.
-
.extract_colors(text, mode = :both) ⇒ Object
Extract named or hex colors from the provided text.
-
.from_html(html_color) ⇒ Object
Creates a RGB color object from an HTML color descriptor (e.g., ‘“fed”` or `“#cabbed;”`.
-
.from_percentage(*args, **kwargs) ⇒ Object
Creates a RGB color object from percentage values (0.0 .. 100.0).
-
.from_values(*args, **kwargs) ⇒ Object
Creates a RGB color object from the standard three byte range (0 .. 255).
Instance Method Summary collapse
-
#adjust_brightness(percent) ⇒ Object
Returns a new RGB color with the brightness adjusted by the specified percentage via Color::HSL.
-
#adjust_hue(percent) ⇒ Object
Returns a new RGB color with the hue adjusted by the specified percentage via Color::HSL.
-
#adjust_saturation(percent) ⇒ Object
Returns a new RGB color with the saturation adjusted by the specified percentage via Color::HSL.
-
#blue ⇒ Object
:nodoc:.
-
#blue_p ⇒ Object
:nodoc:.
-
#brightness ⇒ Object
Returns the brightness value for a color, a number between 0..1.
-
#closest_match(color_list, *args, **kwargs) ⇒ Object
Determines the closest match to this color from a list of provided colors or
nilifcolor_listis empty or no color is found within thethreshold_distance. -
#coerce(other) ⇒ Object
Coerces the other Color object into RGB.
-
#contrast(other, *args, **kwargs) ⇒ Object
Outputs how much contrast this color has with another RGB color.
-
#css(alpha: nil) ⇒ Object
Present the color as an CSS
rgbfunction with optionalalpha. -
#darken_by(percent) ⇒ Object
Mix the RGB hue with black so that the RGB hue is the specified percentage of the resulting color.
-
#deconstruct_keys(_keys) ⇒ Object
:nodoc:.
-
#delta_e2000(other) ⇒ Object
Computes the ΔE* 2000 difference via Color::CIELAB.
-
#delta_e94 ⇒ Object
The Delta E (CIE94) algorithm en.wikipedia.org/wiki/Color_difference#CIE94.
-
#green ⇒ Object
:nodoc:.
-
#green_p ⇒ Object
:nodoc:.
-
#hex ⇒ Object
Present the color as an HTML/CSS RGB hex triplet (
ccddee). -
#html ⇒ Object
Present the color as an HTML/CSS color string (
#ccddee). -
#initialize(r:, g:, b:, names: nil) ⇒ RGB
constructor
Creates a RGB color object from fractional values (0.0 .. 1.0).
-
#inspect ⇒ Object
:nodoc:.
-
#lighten_by(percent) ⇒ Object
Mix the RGB hue with white so that the RGB hue is the specified percentage of the resulting color.
-
#max_rgb_as_grayscale ⇒ Object
Return a Grayscale color object created from the largest of the
r,g, andbvalues. -
#mix_with(mask, opacity) ⇒ Object
Mix the mask color with the current color at the stated opacity percentage (0..100).
-
#name ⇒ Object
:nodoc:.
-
#pretty_print(q) ⇒ Object
:nodoc:.
-
#red ⇒ Object
:nodoc:.
-
#red_p ⇒ Object
:nodoc:.
-
#to_a ⇒ Object
(also: #deconstruct)
:nodoc:.
-
#to_cmyk ⇒ Object
Converts the RGB color to Color::CMYK.
-
#to_grayscale ⇒ Object
Convert RGB to Color::Grayscale via Color::HSL (for the luminance value).
-
#to_hsl ⇒ Object
Converts RGB to Color::HSL.
-
#to_internal ⇒ Object
:nodoc:.
-
#to_lab ⇒ Object
Converts RGB to Color::CIELAB via Color::XYZ.
- #to_rgb ⇒ Object
-
#to_xyz(*args, **kwargs) ⇒ Object
Converts RGB to Color::XYZ using the D65 reference white.
-
#to_yiq ⇒ Object
Converts RGB to Color::YIQ.
Methods included from Color
#==, #components, #css_value, #map, #map_with, normalize, #scale, translate_range, #zip
Constructor Details
#initialize(r:, g:, b:, names: nil) ⇒ RGB
Creates a RGB color object from fractional values (0.0 .. 1.0).
“‘ruby Color::RGB.from_fraction(0.3, 0.2, 0.1) # => RGB [#4d331a] Color::RGB.new(0.3, 0.2, 0.1) # => RGB [#4d331a] Color::RGB[r: 0.3, g: 0.2, b: 0.1] # => RGB [#4d331a] “`
62 63 64 |
# File 'lib/color/rgb.rb', line 62 def initialize(r:, g:, b:, names: nil) super(r: normalize(r), g: normalize(g), b: normalize(b), names: names) end |
Instance Attribute Details
#b ⇒ Object (readonly)
Returns the value of attribute b
48 49 50 |
# File 'lib/color.rb', line 48 def b @b end |
#g ⇒ Object (readonly)
Returns the value of attribute g
48 49 50 |
# File 'lib/color.rb', line 48 def g @g end |
#names ⇒ Object (readonly)
Returns the value of attribute names
48 49 50 |
# File 'lib/color.rb', line 48 def names @names end |
#r ⇒ Object (readonly)
Returns the value of attribute r
48 49 50 |
# File 'lib/color.rb', line 48 def r @r end |
Class Method Details
.__create_named_colors(mod, *colors) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/color/rgb/colors.rb', line 7 def __create_named_colors(mod, *colors) @__by_hex ||= {} @__by_name ||= {} colors.each do |color| color => {rgb:, names:} raise ArgumentError, "Names cannot be empty" if names.nil? || names.empty? used = names - mod.constants.map(&:to_sym) if used.length < names.length raise ArgumentError, "#{names.join(", ")} already defined in #{mod}" end rgb = rgb.with(names: Array(names).flatten.compact.map { _1.to_s.downcase }.sort.uniq) names.each { mod.const_set(_1, rgb) } rgb.names.each { @__by_name[_1] = @__by_name[_1.to_s] = rgb } lower = rgb.name.downcase @__by_name[lower] = @__by_name[lower.to_s] = rgb @__by_hex[rgb.hex] = rgb end end |
.by_css(name_or_hex, &block) ⇒ Object
Return a color as identified by the color name, or by hex.
658 |
# File 'lib/color/rgb.rb', line 658 def by_css(name_or_hex, &block) = by_name(name_or_hex) { by_hex(name_or_hex, &block) } |
.by_hex(hex) ⇒ Object
Find or create a color by an HTML hex code. This differs from the #from_html method in that if the color code matches a named color, the existing color will be returned.
“‘ruby Color::RGB.by_hex(’ff0000’).name # => ‘red’ Color::RGB.by_hex(‘ff0001’).name # => nil “‘
An exception will be raised if the value provided is not found or cannot be interpreted as a valid hex colour.
650 |
# File 'lib/color/rgb.rb', line 650 def by_hex(hex) = __by_hex.fetch(html_hexify(hex)) { from_html(hex) } |
.by_name(name, &block) ⇒ Object
Return a color as identified by the color name.
654 |
# File 'lib/color/rgb.rb', line 654 def by_name(name, &block) = __by_name.fetch(name.to_s.downcase, &block) |
.extract_colors(text, mode = :both) ⇒ Object
Extract named or hex colors from the provided text.
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 |
# File 'lib/color/rgb.rb', line 662 def extract_colors(text, mode = :both) require "color/rgb/colors" text = text.downcase regex = case mode when :name Regexp.union(__by_name.keys) when :hex Regexp.union(__by_hex.keys) when :both Regexp.union(__by_hex.keys + __by_name.keys) else raise ArgumentError, "Unknown mode #{mode}" end text.scan(regex).map { |match| case mode when :name by_name(match) when :hex by_hex(match) when :both by_css(match) end } end |
.from_html(html_color) ⇒ Object
Creates a RGB color object from an HTML color descriptor (e.g., ‘“fed”` or `“#cabbed;”`.
“‘ruby Color::RGB.from_html(“fed”) Color::RGB.from_html(“#fed”) Color::RGB.from_html(“#cabbed”) Color::RGB.from_html(“cabbed”) “`
624 625 626 627 628 629 630 631 632 633 634 635 636 |
# File 'lib/color/rgb.rb', line 624 def from_html(html_color) h = html_color.scan(/\h/i) r, g, b = case h.size when 3 h.map { |v| (v * 2).to_i(16) } when 6 h.each_slice(2).map { |v| v.join.to_i(16) } else raise ArgumentError, "Not a supported HTML color type." end from_values(r, g, b) end |
.from_percentage(*args, **kwargs) ⇒ Object
Creates a RGB color object from percentage values (0.0 .. 100.0).
“‘ruby Color::RGB.from_percentage(10, 20, 30) “`
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 |
# File 'lib/color/rgb.rb', line 566 def from_percentage(*args, **kwargs) r, g, b, names = case [args, kwargs] in [[r, g, b], {}] [r, g, b, nil] in [[_, _, _, _], {}] args in [[], {r:, g:, b:}] [r, g, b, nil] in [[], {r:, g:, b:, names:}] [r, g, b, names] else new(*args, **kwargs) end new(r: r / 100.0, g: g / 100.0, b: b / 100.0, names: names) end |
.from_values(*args, **kwargs) ⇒ Object
Creates a RGB color object from the standard three byte range (0 .. 255).
“‘ruby Color::RGB.from_values(32, 64, 128) Color::RGB.from_values(0x20, 0x40, 0x80) “`
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 |
# File 'lib/color/rgb.rb', line 590 def from_values(*args, **kwargs) r, g, b, names = case [args, kwargs] in [[r, g, b], {}] [r, g, b, nil] in [[_, _, _, _], {}] args in [[], {r:, g:, b:}] [r, g, b, nil] in [[], {r:, g:, b:, names:}] [r, g, b, names] else new(*args, **kwargs) end new(r: r / 255.0, g: g / 255.0, b: b / 255.0, names: names) end |
Instance Method Details
#adjust_brightness(percent) ⇒ Object
Returns a new RGB color with the brightness adjusted by the specified percentage via Color::HSL. Negative percentages will darken the color; positive percentages will brighten the color.
“‘ruby dark_blue = Color::RGB::DarkBlue # => RGB [#00008b] dark_blue.adjust_brightness(10) # => RGB [#000099] dark_blue.adjust_brightness(-10) # => RGB [#00007d] “`
320 321 322 323 |
# File 'lib/color/rgb.rb', line 320 def adjust_brightness(percent) hsl = to_hsl hsl.with(l: hsl.l * percent_adjustment(percent)).to_rgb end |
#adjust_hue(percent) ⇒ Object
Returns a new RGB color with the hue adjusted by the specified percentage via Color::HSL. Negative percentages will reduce the hue; positive percentages will increase the hue.
“‘ruby dark_blue = Color::RGB::DarkBlue # => RGB [#00008b] dark_blue.adjust_hue(10) # => RGB [#38008b] dark_blue.adjust_hue(-10) # => RGB [#00388b] “`
350 351 352 353 |
# File 'lib/color/rgb.rb', line 350 def adjust_hue(percent) hsl = to_hsl hsl.with(h: hsl.h * percent_adjustment(percent)).to_rgb end |
#adjust_saturation(percent) ⇒ Object
Returns a new RGB color with the saturation adjusted by the specified percentage via Color::HSL. Negative percentages will reduce the saturation; positive percentages will increase the saturation.
“‘ruby dark_blue = Color::RGB::DarkBlue # => RGB [#00008b] dark_blue.adjust_saturation(10) # => RGB [#00008b] dark_blue.adjust_saturation(-10) # => RGB [#070784] “`
335 336 337 338 |
# File 'lib/color/rgb.rb', line 335 def adjust_saturation(percent) hsl = to_hsl hsl.with(s: hsl.s * percent_adjustment(percent)).to_rgb end |
#blue ⇒ Object
:nodoc:
430 |
# File 'lib/color/rgb.rb', line 430 def blue = normalize(b * 255.0, 0.0..255.0) # :nodoc: |
#blue_p ⇒ Object
:nodoc:
433 |
# File 'lib/color/rgb.rb', line 433 def blue_p = normalize(b * 100.0, 0.0..100.0) # :nodoc: |
#brightness ⇒ Object
Returns the brightness value for a color, a number between 0..1.
Based on the Y value of Color::YIQ encoding, representing luminosity, or perceived brightness.
308 |
# File 'lib/color/rgb.rb', line 308 def brightness = to_yiq.y |
#closest_match(color_list, *args, **kwargs) ⇒ Object
Determines the closest match to this color from a list of provided colors or nil if color_list is empty or no color is found within the threshold_distance.
The default search uses the CIE ΔE* 1994 algorithm (CIE94) to find near matches based on the perceived visual differences between the colors. The default value for algorithm is :delta_e94.
threshold_distance is used to determine the minimum color distance permitted. Uses the CIE ΔE* 1994 algorithm (CIE94) to find near matches based on perceived visual color. The default value (1000.0) is an arbitrarily large number. The values :jnd and :just_noticeable may be passed as the threshold_distance to use the value 2.3.
All ΔE* formulae were designed to use 1.0 as a “just noticeable difference” (JND), but CIE ΔE*ab 1976 defined JND as 2.3.
:call-seq:
closest_match(color_list, algorithm: :delta_e94, threshold_distance: 1000.0)
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
# File 'lib/color/rgb.rb', line 374 def closest_match(color_list, *args, **kwargs) color_list = [color_list].flatten(1) return nil if color_list.empty? algorithm = kwargs[:algorithm] || args.first || :delta_e94 threshold_distance = kwargs[:threshold_distance] || args[1] || 1000.0 threshold_distance = case threshold_distance when :jnd, :just_noticeable 2.3 else threshold_distance.to_f end closest_distance = threshold_distance best_match = nil color_list.each do |c| distance = contrast(c, algorithm) if distance < closest_distance closest_distance = distance best_match = c end end best_match end |
#coerce(other) ⇒ Object
Coerces the other Color object into RGB.
90 |
# File 'lib/color/rgb.rb', line 90 def coerce(other) = other.to_rgb |
#contrast(other, *args, **kwargs) ⇒ Object
Outputs how much contrast this color has with another RGB color.
The delta_e94 algorithm uses ΔE*94 for contrast calculations and the delta_e2000 algorithm uses ΔE*2000.
The naive algorithm treats the foreground and background colors as the same. Any result over about 0.22 should have a high likelihood of being legible, but the larger the difference, the more contrast. Otherwise, to be safe go with something > 0.3.
:call-seq:
contrast(other, algorithm: :naive)
contrast(other, algorithm: :delta_e94)
contrast(other, algorithm: :delta_e2000)
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 |
# File 'lib/color/rgb.rb', line 490 def contrast(other, *args, **kwargs) other = coerce(other) algorithm = kwargs[:algorithm] || args.first || :naive case algorithm when :delta_e94 delta_e94(other) when :delta_e2000 delta_e2000(other) when :naive # The following numbers have been set with some care. ((diff_brightness(other) * 0.65) + (diff_hue(other) * 0.20) + (diff_luminosity(other) * 0.15)) else raise ARgumentError, "Unknown algorithm #{algorithm.inspect}" end end |
#css(alpha: nil) ⇒ Object
Present the color as an CSS rgb function with optional alpha.
“‘ruby rgb = Color::RGB.from_percentage(0, 50, 100) rgb.css # => rgb(0 50.00% 100.00%) rgb.css(alpha: 0.5) # => rgb(0 50.00% 100.00% / 0.50) “`
265 266 267 268 269 270 |
# File 'lib/color/rgb.rb', line 265 def css(alpha: nil) params = [css_value(red_p, :percent), css_value(green_p, :percent), css_value(blue_p, :percent)].join(" ") params = "#{params} / #{css_value(alpha)}" if alpha "rgb(#{params})" end |
#darken_by(percent) ⇒ Object
Mix the RGB hue with black so that the RGB hue is the specified percentage of the resulting color.
Strictly speaking, this isn’t a darken_by operation, but it mostly works.
288 |
# File 'lib/color/rgb.rb', line 288 def darken_by(percent) = mix_with(Color::RGB::Black000, percent) |
#deconstruct_keys(_keys) ⇒ Object
:nodoc:
470 |
# File 'lib/color/rgb.rb', line 470 def deconstruct_keys(_keys) = {r:, g:, b:, red:, green:, blue:} # :nodoc: |
#delta_e2000(other) ⇒ Object
Computes the ΔE* 2000 difference via Color::CIELAB. See Color::CIELAB#delta_e2000.
274 |
# File 'lib/color/rgb.rb', line 274 def delta_e2000(other) = to_lab.delta_e2000(coerce(other).to_lab) |
#delta_e94 ⇒ Object
The Delta E (CIE94) algorithm en.wikipedia.org/wiki/Color_difference#CIE94
There is a newer version, CIEDE2000, that uses slightly more complicated math, but addresses “the perceptual uniformity issue” left lingering by the CIE94 algorithm.
Since our source is treated as sRGB, we use the “graphic arts” presets for k_L, k_1, and k_2
The calculations go through LCH(ab). (?)
See also www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html
415 |
# File 'lib/color/rgb.rb', line 415 def delta_e94(...) = to_lab.delta_e94(...) |
#green ⇒ Object
:nodoc:
424 |
# File 'lib/color/rgb.rb', line 424 def green = normalize(g * 255.0, 0.0..255.0) # :nodoc: |
#green_p ⇒ Object
:nodoc:
427 |
# File 'lib/color/rgb.rb', line 427 def green_p = normalize(g * 100.0, 0.0..100.0) # :nodoc: |
#hex ⇒ Object
Present the color as an HTML/CSS RGB hex triplet (ccddee).
247 248 249 |
# File 'lib/color/rgb.rb', line 247 def hex "%02x%02x%02x" % [red, green, blue].map(&:round) end |
#html ⇒ Object
Present the color as an HTML/CSS color string (#ccddee).
253 254 255 |
# File 'lib/color/rgb.rb', line 253 def html "##{hex}" end |
#inspect ⇒ Object
:nodoc:
441 |
# File 'lib/color/rgb.rb', line 441 def inspect = names ? "RGB [#{html}] {#{names.join(" ")}}" : "RGB [#{html}]" # :nodoc: |
#lighten_by(percent) ⇒ Object
Mix the RGB hue with white so that the RGB hue is the specified percentage of the resulting color.
Strictly speaking, this isn’t a lighten_by operation, but it mostly works.
281 |
# File 'lib/color/rgb.rb', line 281 def lighten_by(percent) = mix_with(Color::RGB::WhiteFFF, percent) |
#max_rgb_as_grayscale ⇒ Object
Return a Grayscale color object created from the largest of the r, g, and b values.
438 |
# File 'lib/color/rgb.rb', line 438 def max_rgb_as_grayscale = Color::Grayscale.from_fraction([r, g, b].max) |
#mix_with(mask, opacity) ⇒ Object
Mix the mask color with the current color at the stated opacity percentage (0..100).
292 293 294 295 296 297 298 299 300 301 |
# File 'lib/color/rgb.rb', line 292 def mix_with(mask, opacity) opacity = normalize(opacity / 100.0) mask = coerce(mask) with( r: (r * opacity) + (mask.r * (1 - opacity)), g: (g * opacity) + (mask.g * (1 - opacity)), b: (b * opacity) + (mask.b * (1 - opacity)) ) end |
#name ⇒ Object
:nodoc:
81 82 83 84 85 86 |
# File 'lib/color/rgb.rb', line 81 def name # :nodoc: name = names&.first return name if name self.class.send(:__by_hex)[hex]&.name if defined?(Color::RGB::Metallic) end |
#pretty_print(q) ⇒ Object
:nodoc:
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'lib/color/rgb.rb', line 444 def pretty_print(q) # :nodoc: q.text "RGB" q.breakable q.group 2, "[", "]" do q.text html end if names q.breakable q.group 2, "{", "}" do last = names.last names.each { q.text _1 q.fill_breakable unless _1 == last } end end end |
#red ⇒ Object
:nodoc:
418 |
# File 'lib/color/rgb.rb', line 418 def red = normalize(r * 255.0, 0.0..255.0) # :nodoc: |
#red_p ⇒ Object
:nodoc:
421 |
# File 'lib/color/rgb.rb', line 421 def red_p = normalize(r * 100.0, 0.0..100.0) # :nodoc: |
#to_a ⇒ Object Also known as: deconstruct
:nodoc:
464 |
# File 'lib/color/rgb.rb', line 464 def to_a = [red, green, blue] # :nodoc: |
#to_cmyk ⇒ Object
Converts the RGB color to Color::CMYK.
Most color experts strongly suggest that this is not a good idea (some suggesting that it’s a very bad idea). CMYK represents additive percentages of inks on white paper, whereas RGB represents mixed color intensities on an unlit (black) screen.
-
Convert the R, G, and B components to C, M, and Y components.
c = 1.0 - r m = 1.0 - g y = 1.0 - b -
Compute the minimum amount of black (K) required to smooth the color in inks.
k = min(c, m, y) -
Perform undercolor removal on the C, M, and Y components of the colors because less of each color is needed for each bit of black. Also, regenerate the black (K) based on the undercolor removal so that the color is more accurately represented in ink.
c = min(1.0, max(0.0, c - UCR(k))) m = min(1.0, max(0.0, m - UCR(k))) y = min(1.0, max(0.0, y - UCR(k))) k = min(1.0, max(0.0, BG(k)))
The undercolor removal function and the black generation functions return a value based on the brightness of the RGB color.
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/color/rgb.rb', line 120 def to_cmyk(...) c = 1.0 - r.to_f m = 1.0 - g.to_f y = 1.0 - b.to_f k = [c, m, y].min k -= (k * brightness) c = normalize(c - k) m = normalize(m - k) y = normalize(y - k) k = normalize(k) Color::CMYK.from_fraction(c, m, y, k) end |
#to_grayscale ⇒ Object
Convert RGB to Color::Grayscale via Color::HSL (for the luminance value).
141 |
# File 'lib/color/rgb.rb', line 141 def to_grayscale(...) = Color::Grayscale.from_fraction(to_hsl.l) |
#to_hsl ⇒ Object
Converts RGB to Color::HSL.
The conversion here is based on formulas from www.easyrgb.com/math.php and elsewhere.
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/color/rgb.rb', line 157 def to_hsl(...) min, max = [r, g, b].minmax delta = (max - min).to_f l = (max + min) / 2.0 if near_zero?(delta) # close to 0.0, so it's a gray h = 0 s = 0 else s = if near_zero_or_less?(l - 0.5) delta / (max + min).to_f else delta / (2 - max - min).to_f end # This is based on the conversion algorithm from # https://en.wikipedia.org/wiki/HSV_color_space#Conversion_from_RGB_to_HSL_or_HSV # Contributed by Adam Johnson sixth = 1 / 6.0 if r == max # near_zero_or_less?(r - max) h = (sixth * ((g - b) / delta)) h += 1.0 if g < b elsif g == max # near_zero_or_less(g - max) h = (sixth * ((b - r) / delta)) + (1.0 / 3.0) elsif b == max # near_zero_or_less?(b - max) h = (sixth * ((r - g) / delta)) + (2.0 / 3.0) end h += 1 if h < 0 h -= 1 if h > 1 end Color::HSL.from_fraction(h, s, l) end |
#to_internal ⇒ Object
:nodoc:
473 |
# File 'lib/color/rgb.rb', line 473 def to_internal = [r, g, b] # :nodoc: |
#to_lab ⇒ Object
Converts RGB to Color::CIELAB via Color::XYZ.
Based on the [XYZ to CIELAB] formula presented by Bruce Lindbloom.
[xyztolab]: www.brucelindbloom.com/index.html?Eqn_XYZ_to_Lab.html
The conversion is performed assuming the RGB value is in the sRGB color space. No other RGB color spaces are currently supported. By default, uses the D65 reference white for the conversion.
:call-seq:
to_lab(color_space: :sRGB, white: Color::XYZ::D65)
243 |
# File 'lib/color/rgb.rb', line 243 def to_lab(...) = to_xyz(...).to_lab(...) |
#to_rgb ⇒ Object
137 |
# File 'lib/color/rgb.rb', line 137 def to_rgb(...) = self |
#to_xyz(*args, **kwargs) ⇒ Object
Converts RGB to Color::XYZ using the D65 reference white. This is based on conversion formulas presented by Bruce Lindbloom, in particular [RGB to XYZ].
[rgbxyz]: www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html
The conversion is performed assuming the RGB value is in the sRGB color space. No other RGB color spaces are currently supported.
:call-seq:
to_xyz(color_space: :sRGB)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/color/rgb.rb', line 204 def to_xyz(*args, **kwargs) color_space = kwargs[:color_space] || args.first || :sRGB case color_space.to_s.downcase when "srgb" # Inverse sRGB companding. Linearizes RGB channels with respect to energy. rr, gg, bb = [r, g, b].map { if _1 > 0.04045 (((_1 + 0.055) / 1.055)**2.4) else (_1 / 12.92) end * 100.0 } # Convert using the RGB/XYZ matrix at: # http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html#WSMatrices Color::XYZ.from_values( rr * 0.4124564 + gg * 0.3575761 + bb * 0.1804375, rr * 0.2126729 + gg * 0.7151522 + bb * 0.0721750, rr * 0.0193339 + gg * 0.1191920 + bb * 0.9503041 ) else raise ArgumentError, "Unsupported color space #{color_space}." end end |