module ChunkyPNG::Color

The Color module defines methods for handling colors. Within the ChunkyPNG library, the concepts of pixels and colors are both used, and they are both represented by a Integer.

Pixels/colors are represented in RGBA components. Each of the four components is stored with a depth of 8 bits (maximum value = 255 = {ChunkyPNG::Color::MAX}). Together, these components are stored in a 4-byte Integer.

A color will always be represented using these 4 components in memory. When the image is encoded, a more suitable representation can be used (e.g. rgb, grayscale, palette-based), for which several conversion methods are provided in this module.

Constants

BLACK

@return [Integer] Black pixel/color

HEX3_COLOR_REGEXP

@private @return [Regexp] The regexp to parse 3-digit hex color values.

HEX6_COLOR_REGEXP

@private @return [Regexp] The regexp to parse 6- and 8-digit hex color values.

HTML_COLOR_REGEXP

@private @return [Regexp] The regexp to parse named color values.

MAX

@return [Integer] The maximum value of each color component.

MAX_EUCLIDEAN_DISTANCE_RGBA

Could be simplified as MAX * 2, but this format mirrors the math in {#euclidean_distance_rgba} @return [Float] The maximum Euclidean distance of two RGBA colors.

PREDEFINED_COLORS

@return [Hash<Symbol, Integer>] All the predefined color names in HTML.

TRANSPARENT

@return [Integer] Fully transparent pixel/color

WHITE

@return [Integer] White pixel/color

Public Instance Methods

a(value) click to toggle source

Returns the alpha channel value for the color value.

@param [Integer] value The color value. @return [Integer] A value between 0 and MAX.

    # File lib/chunky_png/color.rb
296 def a(value)
297   value & 0x000000ff
298 end
alpha_decomposable?(color, mask, bg, tolerance = 1) click to toggle source

Checks whether an alpha channel value can successfully be composed given the resulting color, the mask color and a background color, all of which should be opaque.

@param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being

composed

@param [Integer] bg The background color on which the color was composed. @param [Integer] tolerance The decomposition tolerance level, a value

between 0 and 255

@return [Boolean] True if the alpha component can be decomposed

successfully.

@see decompose_alpha

    # File lib/chunky_png/color.rb
500 def alpha_decomposable?(color, mask, bg, tolerance = 1)
501   components = decompose_alpha_components(color, mask, bg)
502   sum = components.inject(0) { |a,b| a + b }
503   max = components.max * 3
504   components.max <= 255 && components.min >= 0 && (sum + tolerance * 3) >= max
505 end
b(value) click to toggle source

Returns the blue-component from the color value.

@param [Integer] value The color value. @return [Integer] A value between 0 and MAX.

    # File lib/chunky_png/color.rb
288 def b(value)
289   (value & 0x0000ff00) >> 8
290 end
blend(fg, bg) click to toggle source

Blends the foreground and background color by taking the average of the components.

@param [Integer] fg The foreground color. @param [Integer] bg The foreground color. @return [Integer] The blended color.

    # File lib/chunky_png/color.rb
403 def blend(fg, bg)
404   (fg + bg) >> 1
405 end
compose(fg, bg)
Alias for: compose_quick
compose_precise(fg, bg) click to toggle source

Composes two colors with an alpha channel using floating point math.

This method uses more precise floating point math, but this precision is lost when the result is converted back to an integer. Because it is slower than the version based on integer math, that version is preferred.

@param [Integer] fg The foreground color. @param [Integer] bg The background color. @return [Integer] The composited color. @see ChunkyPNG::Color#compose_quick

    # File lib/chunky_png/color.rb
380 def compose_precise(fg, bg)
381   return fg if opaque?(fg) || fully_transparent?(bg)
382   return bg if fully_transparent?(fg)
383 
384   fg_a  = a(fg).to_f / MAX
385   bg_a  = a(bg).to_f / MAX
386   a_com = (1.0 - fg_a) * bg_a
387 
388   new_r = (fg_a * r(fg) + a_com * r(bg)).round
389   new_g = (fg_a * g(fg) + a_com * g(bg)).round
390   new_b = (fg_a * b(fg) + a_com * b(bg)).round
391   new_a = ((fg_a + a_com) * MAX).round
392   rgba(new_r, new_g, new_b, new_a)
393 end
compose_quick(fg, bg) click to toggle source

Composes two colors with an alpha channel using integer math.

This version is faster than the version based on floating point math, so this compositing function is used by default.

@param [Integer] fg The foreground color. @param [Integer] bg The background color. @return [Integer] The composited color. @see ChunkyPNG::Color#compose_precise

    # File lib/chunky_png/color.rb
358 def compose_quick(fg, bg)
359   return fg if opaque?(fg) || fully_transparent?(bg)
360   return bg if fully_transparent?(fg)
361 
362   a_com = int8_mult(0xff - a(fg), a(bg))
363   new_r = int8_mult(a(fg), r(fg)) + int8_mult(a_com, r(bg))
364   new_g = int8_mult(a(fg), g(fg)) + int8_mult(a_com, g(bg))
365   new_b = int8_mult(a(fg), b(fg)) + int8_mult(a_com, b(bg))
366   new_a = a(fg) + a_com
367   rgba(new_r, new_g, new_b, new_a)
368 end
Also aliased as: compose
decompose_alpha(color, mask, bg) click to toggle source

Decomposes the alpha channel value given the resulting color, the mask color and a background color, all of which should be opaque.

Make sure to call {#alpha_decomposable?} first to see if the alpha channel value can successfully decomposed with a given tolerance, otherwise the return value of this method is undefined.

@param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being

composed

@param [Integer] bg The background color on which the color was composed. @return [Integer] The best fitting alpha channel, a value between 0 and

255

@see alpha_decomposable?

    # File lib/chunky_png/color.rb
521 def decompose_alpha(color, mask, bg)
522   components = decompose_alpha_components(color, mask, bg)
523   (components.inject(0) { |a,b| a + b } / 3.0).round
524 end
decompose_alpha_component(channel, color, mask, bg) click to toggle source

Decomposes an alpha channel for either the r, g or b color channel. @param [:r, :g, :b] channel The channel to decompose the alpha channel

from.

@param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being

composed

@param [Integer] bg The background color on which the color was composed. @return [Integer] The decomposed alpha value for the channel.

    # File lib/chunky_png/color.rb
534 def decompose_alpha_component(channel, color, mask, bg)
535   cc, mc, bc = send(channel, color), send(channel, mask), send(channel, bg)
536 
537   return 0x00 if bc == cc
538   return 0xff if bc == mc
539   return 0xff if cc == mc
540 
541   (((bc - cc).to_f / (bc - mc).to_f) * MAX).round
542 end
decompose_alpha_components(color, mask, bg) click to toggle source

Decomposes the alpha channels for the r, g and b color channel. @param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being

composed

@param [Integer] bg The background color on which the color was composed. @return [Array<Integer>] The decomposed alpha values for the r, g and b

channels.
    # File lib/chunky_png/color.rb
551 def decompose_alpha_components(color, mask, bg)
552   [
553     decompose_alpha_component(:r, color, mask, bg),
554     decompose_alpha_component(:g, color, mask, bg),
555     decompose_alpha_component(:b, color, mask, bg)
556   ]
557 end
decompose_color(color, mask, bg, tolerance = 1) click to toggle source

Decomposes a color, given a color, a mask color and a background color. The returned color will be a variant of the mask color, with the alpha channel set to the best fitting value. This basically is the reverse operation if alpha composition.

If the color cannot be decomposed, this method will return the fully transparent variant of the mask color.

@param [Integer] color The color that was the result of compositing. @param [Integer] mask The opaque variant of the color that was being

composed

@param [Integer] bg The background color on which the color was composed. @param [Integer] tolerance The decomposition tolerance level, a value

between 0 and 255

@return [Integer] The decomposed color, a variant of the masked color

with the alpha channel set to an appropriate value.
    # File lib/chunky_png/color.rb
479 def decompose_color(color, mask, bg, tolerance = 1)
480   if alpha_decomposable?(color, mask, bg, tolerance)
481     mask & 0xffffff00 | decompose_alpha(color, mask, bg)
482   else
483     mask & 0xffffff00
484   end
485 end
euclidean_distance_rgba(pixel_after, pixel_before) click to toggle source

Compute the Euclidean distance between 2 colors in RGBA

This method simply takes the Euclidean distance between the RGBA channels of 2 colors, which gives us a measure of how different the two colors are.

Although it would be more perceptually accurate to calculate a proper Delta E in Lab colorspace, this method should serve many use-cases while avoiding the overhead of converting RGBA to Lab.

@param pixel_after [Integer] @param pixel_before [Integer] @return [Float]

    # File lib/chunky_png/color.rb
716 def euclidean_distance_rgba(pixel_after, pixel_before)
717   return 0.0 if pixel_after == pixel_before
718 
719   Math.sqrt(
720     (r(pixel_after) - r(pixel_before))**2 +
721     (g(pixel_after) - g(pixel_before))**2 +
722     (b(pixel_after) - b(pixel_before))**2 +
723     (a(pixel_after) - a(pixel_before))**2
724   )
725 end
fade(color, factor) click to toggle source

Lowers the intensity of a color, by lowering its alpha by a given factor. @param [Integer] color The color to adjust. @param [Integer] factor Fade factor as an integer between 0 and 255. @return [Integer] The faded color.

    # File lib/chunky_png/color.rb
458 def fade(color, factor)
459   new_alpha = int8_mult(a(color), factor)
460   (color & 0xffffff00) | new_alpha
461 end
from_hex(hex_value, opacity = nil) click to toggle source

Creates a color by converting it from a string in hex notation.

It supports colors with (rrggbbaa) or without (rrggbb) alpha channel as well as the 3-digit short format (rgb) for those without. Color strings may include the prefix “0x” or “#”.

@param [String] str The color in hex notation. @return [Integer] The

converted color value.

@param [Integer] opacity The opacity value for the color. Overrides any

opacity value given in the hex value if given.

@return [Integer] The color value. @raise [ArgumentError] if the value given is not a hex color notation.

    # File lib/chunky_png/color.rb
166 def from_hex(hex_value, opacity = nil)
167   base_color = case hex_value
168                when HEX3_COLOR_REGEXP
169                  $1.gsub(/([0-9a-f])/i, '\1\1').hex << 8
170                when HEX6_COLOR_REGEXP
171                  $1.hex << 8
172                else
173                  raise ArgumentError, "Not a valid hex color notation: #{hex_value.inspect}!"
174                end
175   opacity  ||= $2 ? $2.hex : 0xff
176   base_color | opacity
177 end
from_hsb(hue, saturation, value, alpha = 255)
Alias for: from_hsv
from_hsl(hue, saturation, lightness, alpha = 255) click to toggle source

Creates a new color from an HSL triple.

This implementation follows the modern convention of 0 degrees hue indicating red.

@param [Fixnum] hue The hue component (0-360) @param [Fixnum] saturation The saturation component (0-1) @param [Fixnum] lightness The lightness component (0-1) @param [Fixnum] alpha Defaults to opaque (255). @return [Integer] The newly constructed color value. @raise [ArgumentError] if the hsl triple is invalid. @see en.wikipedia.org/wiki/HSL_and_HSV

    # File lib/chunky_png/color.rb
217 def from_hsl(hue, saturation, lightness, alpha = 255)
218   raise ArgumentError, "Hue #{hue} was not between 0 and 360" unless (0..360).include?(hue)
219   raise ArgumentError, "Saturation #{saturation} was not between 0 and 1" unless (0..1).include?(saturation)
220   raise ArgumentError, "Lightness #{lightness} was not between 0 and 1" unless (0..1).include?(lightness)
221   chroma = (1 - (2 * lightness - 1).abs) * saturation
222   rgb    = cylindrical_to_cubic(hue, saturation, lightness, chroma)
223   rgb.map! { |component| ((component + lightness - 0.5 * chroma) * 255).to_i }
224   rgb << alpha
225   self.rgba(*rgb)
226 end
from_hsv(hue, saturation, value, alpha = 255) click to toggle source

Creates a new color from an HSV triple.

Create a new color using an HSV (sometimes also called HSB) triple. The words `value` and `brightness` are used interchangeably and synonymously in descriptions of this colorspace. This implementation follows the modern convention of 0 degrees hue indicating red.

@param [Fixnum] hue The hue component (0-360) @param [Fixnum] saturation The saturation component (0-1) @param [Fixnum] value The value (brightness) component (0-1) @param [Fixnum] alpha Defaults to opaque (255). @return [Integer] The newly constructed color value. @raise [ArgumentError] if the hsv triple is invalid. @see en.wikipedia.org/wiki/HSL_and_HSV

    # File lib/chunky_png/color.rb
193 def from_hsv(hue, saturation, value, alpha = 255)
194   raise ArgumentError, "Hue must be between 0 and 360" unless (0..360).include?(hue)
195   raise ArgumentError, "Saturation must be between 0 and 1" unless (0..1).include?(saturation)
196   raise ArgumentError, "Value/brightness must be between 0 and 1" unless (0..1).include?(value)
197   chroma = value * saturation
198   rgb    = cylindrical_to_cubic(hue, saturation, value, chroma)
199   rgb.map! { |component| ((component + value - chroma) * 255).to_i }
200   rgb << alpha
201   self.rgba(*rgb)
202 end
Also aliased as: from_hsb
from_rgb_stream(stream, pos = 0) click to toggle source

Creates a color by unpacking an rgb triple from a string.

@param [String] stream The string to load the color from. It should be

at least 3 + pos bytes long.

@param [Integer] pos The position in the string to load the triple from. @return [Integer] The newly constructed color value.

    # File lib/chunky_png/color.rb
140 def from_rgb_stream(stream, pos = 0)
141   rgb(*stream.unpack("@#{pos}C3"))
142 end
from_rgba_stream(stream, pos = 0) click to toggle source

Creates a color by unpacking an rgba triple from a string

@param [String] stream The string to load the color from. It should be

at least 4 + pos bytes long.

@param [Integer] pos The position in the string to load the triple from. @return [Integer] The newly constructed color value.

    # File lib/chunky_png/color.rb
150 def from_rgba_stream(stream, pos = 0)
151   rgba(*stream.unpack("@#{pos}C4"))
152 end
fully_transparent?(value) click to toggle source

Returns true if this color is fully transparent.

@param [Integer] value The color to test. @return [true, false] True if the alpha channel equals 0.

    # File lib/chunky_png/color.rb
327 def fully_transparent?(value)
328   a(value) == 0x00000000
329 end
g(value) click to toggle source

Returns the green-component from the color value.

@param [Integer] value The color value. @return [Integer] A value between 0 and MAX.

    # File lib/chunky_png/color.rb
280 def g(value)
281   (value & 0x00ff0000) >> 16
282 end
grayscale(teint) click to toggle source

Creates a new color using a grayscale teint. @param [Integer] teint The grayscale teint (0-255), will be used as r, g,

and b value.

@return [Integer] The newly constructed color value.

    # File lib/chunky_png/color.rb
117 def grayscale(teint)
118   teint << 24 | teint << 16 | teint << 8 | 0xff
119 end
grayscale?(value) click to toggle source

Returns true if this color is fully transparent.

@param [Integer] value The color to test. @return [true, false] True if the r, g and b component are equal.

    # File lib/chunky_png/color.rb
319 def grayscale?(value)
320   r(value) == b(value) && b(value) == g(value)
321 end
grayscale_alpha(teint, a) click to toggle source

Creates a new color using a grayscale teint and alpha value. @param [Integer] teint The grayscale teint (0-255), will be used as r, g,

and b value.

@param [Integer] a The opacity (0-255) @return [Integer] The newly constructed color value.

    # File lib/chunky_png/color.rb
126 def grayscale_alpha(teint, a)
127   teint << 24 | teint << 16 | teint << 8 | a
128 end
grayscale_teint(color) click to toggle source

Calculates the grayscale teint of an RGB color.

@param [Integer] color The color to convert. @return [Integer] The grayscale teint of the input color, 0-255.

    # File lib/chunky_png/color.rb
435 def grayscale_teint(color)
436   (r(color) * 0.3 + g(color) * 0.59 + b(color) * 0.11).round
437 end
html_color(color_name, opacity = nil) click to toggle source

Gets a color value based on a HTML color name.

The color name is flexible. E.g. 'yellowgreen', 'Yellow green', 'YellowGreen', 'YELLOW_GREEN' and :yellow_green will all return the same color value.

You can include a opacity level in the color name (e.g. 'red @ 0.5') or give an explicit opacity value as second argument. If no opacity value is given, the color will be fully opaque.

@param [Symbol, String] color_name The color name. It may include an

opacity specifier like <tt>@ 0.8</tt> to set the color's opacity.

@param [Integer] opacity The opacity value for the color between 0 and

255. Overrides any opacity value given in the color name.

@return [Integer] The color value. @raise [ChunkyPNG::Exception] If the color name was not recognized.

    # File lib/chunky_png/color.rb
903 def html_color(color_name, opacity = nil)
904   if color_name.to_s =~ HTML_COLOR_REGEXP
905     opacity ||= $2 ? ($2.to_f * 255.0).round : 0xff
906     base_color_name = $1.gsub(/[^a-z]+/i, '').downcase.to_sym
907     return PREDEFINED_COLORS[base_color_name] | opacity if PREDEFINED_COLORS.has_key?(base_color_name)
908   end
909   raise ArgumentError, "Unknown color name #{color_name}!"
910 end
int8_mult(a, b) click to toggle source

Multiplies two fractions using integer math, where the fractions are stored using an integer between 0 and 255. This method is used as a helper method for compositing colors using integer math.

This is a quicker implementation of ((a * b) / 255.0).round.

@param [Integer] a The first fraction. @param [Integer] b The second fraction. @return [Integer] The result of the multiplication.

    # File lib/chunky_png/color.rb
344 def int8_mult(a, b)
345   t = a * b + 0x80
346   ((t >> 8) + t) >> 8
347 end
interpolate_quick(fg, bg, alpha) click to toggle source

Interpolates the foreground and background colors by the given alpha value. This also blends the alpha channels themselves.

A blending factor of 255 will give entirely the foreground, while a blending factor of 0 will give the background.

@param [Integer] fg The foreground color. @param [Integer] bg The background color. @param [Integer] alpha The blending factor (fixed 8bit) @param [Integer] The interpolated color.

    # File lib/chunky_png/color.rb
417 def interpolate_quick(fg, bg, alpha)
418   return fg if alpha >= 255
419   return bg if alpha <= 0
420 
421   alpha_com = 255 - alpha
422 
423   new_r = int8_mult(alpha, r(fg)) + int8_mult(alpha_com, r(bg))
424   new_g = int8_mult(alpha, g(fg)) + int8_mult(alpha_com, g(bg))
425   new_b = int8_mult(alpha, b(fg)) + int8_mult(alpha_com, b(bg))
426   new_a = int8_mult(alpha, a(fg)) + int8_mult(alpha_com, a(bg))
427 
428   rgba(new_r, new_g, new_b, new_a)
429 end
opaque!(value) click to toggle source

Returns the opaque value of this color by removing the alpha channel. @param [Integer] value The color to transform. @return [Integer] The opaque color

    # File lib/chunky_png/color.rb
311 def opaque!(value)
312   value | 0x000000ff
313 end
opaque?(value) click to toggle source

Returns true if this color is fully opaque.

@param [Integer] value The color to test. @return [true, false] True if the alpha channel equals MAX.

    # File lib/chunky_png/color.rb
304 def opaque?(value)
305   a(value) == 0x000000ff
306 end
parse(source) click to toggle source

Parses a color value given a numeric or string argument.

It supports color numbers, colors in hex notation and named HTML colors.

@param [Integer, String] The color value. @return [Integer] The color value, with the opacity applied if one was

given.
   # File lib/chunky_png/color.rb
84 def parse(source)
85   return source if source.kind_of?(Integer)
86   case source.to_s
87     when /^\d+$/; source.to_s.to_i
88     when HEX3_COLOR_REGEXP, HEX6_COLOR_REGEXP; from_hex(source.to_s)
89     when HTML_COLOR_REGEXP; html_color(source.to_s)
90     else raise ArgumentError, "Don't know how to create a color from #{source.inspect}!"
91   end
92 end
pass_bytesize(color_mode, depth, width, height) click to toggle source

Returns the number of bytes used for an image pass @param [Integer] color_mode The color mode in which the pixels are

stored.

@param [Integer] depth The color depth of the pixels. @param [Integer] width The width of the image pass. @param [Integer] width The height of the image pass. @return [Integer] The number of bytes used per scanline in a datastream.

    # File lib/chunky_png/color.rb
978 def pass_bytesize(color_mode, depth, width, height)
979   return 0 if width == 0 || height == 0
980   (scanline_bytesize(color_mode, depth, width) + 1) * height
981 end
pixel_bitsize(color_mode, depth = 8) click to toggle source

Returns the size in bits of a pixel when it is stored using a given color mode.

@param [Integer] color_mode The color mode in which the pixels are

stored.

@param [Integer] depth The color depth of the pixels. @return [Integer] The number of bytes used per pixel in a datastream.

    # File lib/chunky_png/color.rb
957 def pixel_bitsize(color_mode, depth = 8)
958   samples_per_pixel(color_mode) * depth
959 end
pixel_bytesize(color_mode, depth = 8) click to toggle source

Returns the size in bytes of a pixel when it is stored using a given color mode.

@param [Integer] color_mode The color mode in which the pixels are

stored.

@return [Integer] The number of bytes used per pixel in a datastream.

    # File lib/chunky_png/color.rb
945 def pixel_bytesize(color_mode, depth = 8)
946   return 1 if depth < 8
947   (pixel_bitsize(color_mode, depth) + 7) >> 3
948 end
r(value) click to toggle source

Returns the red-component from the color value.

@param [Integer] value The color value. @return [Integer] A value between 0 and MAX.

    # File lib/chunky_png/color.rb
272 def r(value)
273   (value & 0xff000000) >> 24
274 end
rgb(r, g, b) click to toggle source

Creates a new color using an r, g, b triple. @param [Integer] r The r-component (0-255) @param [Integer] g The g-component (0-255) @param [Integer] b The b-component (0-255) @return [Integer] The newly constructed color value.

    # File lib/chunky_png/color.rb
109 def rgb(r, g, b)
110   r << 24 | g << 16 | b << 8 | 0xff
111 end
rgba(r, g, b, a) click to toggle source

Creates a new color using an r, g, b triple and an alpha value. @param [Integer] r The r-component (0-255) @param [Integer] g The g-component (0-255) @param [Integer] b The b-component (0-255) @param [Integer] a The opacity (0-255) @return [Integer] The newly constructed color value.

    # File lib/chunky_png/color.rb
100 def rgba(r, g, b, a)
101   r << 24 | g << 16 | b << 8 | a
102 end
samples_per_pixel(color_mode) click to toggle source

Returns the number of sample values per pixel. @param [Integer] color_mode The color mode being used. @return [Integer] The number of sample values per pixel.

    # File lib/chunky_png/color.rb
928 def samples_per_pixel(color_mode)
929   case color_mode
930     when ChunkyPNG::COLOR_INDEXED;         1
931     when ChunkyPNG::COLOR_TRUECOLOR;       3
932     when ChunkyPNG::COLOR_TRUECOLOR_ALPHA; 4
933     when ChunkyPNG::COLOR_GRAYSCALE;       1
934     when ChunkyPNG::COLOR_GRAYSCALE_ALPHA; 2
935     else raise ChunkyPNG::NotSupported, "Don't know the number of samples for this colormode: #{color_mode}!"
936   end
937 end
scanline_bytesize(color_mode, depth, width) click to toggle source

Returns the number of bytes used per scanline. @param [Integer] color_mode The color mode in which the pixels are

stored.

@param [Integer] depth The color depth of the pixels. @param [Integer] width The number of pixels per scanline. @return [Integer] The number of bytes used per scanline in a datastream.

    # File lib/chunky_png/color.rb
967 def scanline_bytesize(color_mode, depth, width)
968   ((pixel_bitsize(color_mode, depth) * width) + 7) >> 3
969 end
to_grayscale(color) click to toggle source

Converts a color to a fiting grayscale value. It will conserve the alpha channel.

This method will return a full color value, with the R, G, and B value set to the grayscale teint calcuated from the input color's R, G and B values.

@param [Integer] color The color to convert. @return [Integer] The input color, converted to the best fitting

grayscale.

@see grayscale_teint

    # File lib/chunky_png/color.rb
450 def to_grayscale(color)
451   grayscale_alpha(grayscale_teint(color), a(color))
452 end
to_grayscale_alpha_bytes(color) click to toggle source

Returns an array with the grayscale teint and alpha channel values for this color.

This method expects the color to be grayscale, i.e. r, g, and b value to be equal and uses only the B channel. If you need to convert a color to grayscale first, see {#to_grayscale}.

@param [Integer] color The grayscale color to convert. @return [Array<Integer>] An array with 2 Integer elements. @see to_grayscale

    # File lib/chunky_png/color.rb
695 def to_grayscale_alpha_bytes(color)
696   [b(color), a(color)] # assumption r == g == b
697 end
to_grayscale_bytes(color) click to toggle source

Returns an array with the grayscale teint value for this color.

This method expects the r, g, and b value to be equal, and the alpha channel will be discarded.

@param [Integer] color The grayscale color to convert. @return [Array<Integer>] An array with 1 Integer element.

    # File lib/chunky_png/color.rb
681 def to_grayscale_bytes(color)
682   [b(color)] # assumption r == g == b
683 end
to_hex(color, include_alpha = true) click to toggle source

Returns a string representing this color using hex notation (i.e. rrggbbaa).

@param [Integer] value The color to convert. @return [String] The color in hex notation, starting with a pound sign.

    # File lib/chunky_png/color.rb
568 def to_hex(color, include_alpha = true)
569   include_alpha ? ('#%08x' % color) : ('#%06x' % [color >> 8])
570 end
to_hsb(color, include_alpha = false)
Alias for: to_hsv
to_hsl(color, include_alpha = false) click to toggle source

Returns an array with the separate HSL components of a color.

Because ChunkyPNG internally handles colors as Integers for performance reasons, some rounding occurs when importing or exporting HSL colors whose coordinates are float-based. Because of this rounding, to_hsl and from_hsl may not be perfect inverses.

This implementation follows the modern convention of 0 degrees hue indicating red.

@param [Integer] color The ChunkyPNG color to convert. @param [Boolean] include_alpha Flag indicates whether a fourth element

representing alpha channel should be included in the returned array.

@return [Array] The hue of the color (0-360) @return [Array] The saturation of the color (0-1) @return [Array] The lightness of the color (0-1) @return [Array] Optional fourth element for alpha, included if

include_alpha=true (0-255)

@see en.wikipedia.org/wiki/HSL_and_HSV

    # File lib/chunky_png/color.rb
619 def to_hsl(color, include_alpha = false)
620   hue, chroma, max, min = hue_and_chroma(color)
621   lightness  = 0.5 * (max + min)
622   saturation = chroma.zero? ? 0.0 : chroma.fdiv(1 - (2 * lightness - 1).abs)
623 
624   include_alpha ? [hue, saturation, lightness, a(color)] :
625                   [hue, saturation, lightness]
626 end
to_hsv(color, include_alpha = false) click to toggle source

Returns an array with the separate HSV components of a color.

Because ChunkyPNG internally handles colors as Integers for performance reasons, some rounding occurs when importing or exporting HSV colors whose coordinates are float-based. Because of this rounding, to_hsv and from_hsv may not be perfect inverses.

This implementation follows the modern convention of 0 degrees hue indicating red.

@param [Integer] color The ChunkyPNG color to convert. @param [Boolean] include_alpha Flag indicates whether a fourth element

representing alpha channel should be included in the returned array.

@return [Array] The hue of the color (0-360) @return [Array] The saturation of the color (0-1) @return [Array] The value of the color (0-1) @return [Array] Optional fourth element for alpha, included if

include_alpha=true (0-255)

@see en.wikipedia.org/wiki/HSL_and_HSV

    # File lib/chunky_png/color.rb
591 def to_hsv(color, include_alpha = false)
592   hue, chroma, max, _ = hue_and_chroma(color)
593   value      = max
594   saturation = chroma.zero? ? 0.0 : chroma.fdiv(value)
595 
596   include_alpha ? [hue, saturation, value, a(color)] :
597                   [hue, saturation, value]
598 end
Also aliased as: to_hsb
to_truecolor_alpha_bytes(color) click to toggle source

Returns an array with the separate RGBA values for this color.

@param [Integer] color The color to convert. @return [Array<Integer>] An array with 4 Integer elements.

    # File lib/chunky_png/color.rb
661 def to_truecolor_alpha_bytes(color)
662   [r(color), g(color), b(color), a(color)]
663 end
to_truecolor_bytes(color) click to toggle source

Returns an array with the separate RGB values for this color. The alpha channel will be discarded.

@param [Integer] color The color to convert. @return [Array<Integer>] An array with 3 Integer elements.

    # File lib/chunky_png/color.rb
670 def to_truecolor_bytes(color)
671   [r(color), g(color), b(color)]
672 end

Private Instance Methods

cylindrical_to_cubic(hue, saturation, y_component, chroma) click to toggle source

Convert one HSL or HSV triple and associated chroma to a scaled rgb triple

This method encapsulates the shared mathematical operations needed to convert coordinates from a cylindrical colorspace such as HSL or HSV into coordinates of the RGB colorspace.

Even though chroma values are derived from the other three coordinates, the formula for calculating chroma differs for each colorspace. Since it is calculated differently for each colorspace, it must be passed in as a parameter.

@param [Fixnum] hue The hue-component (0-360) @param [Fixnum] saturation The saturation-component (0-1) @param [Fixnum] y_component The y_component can represent either lightness

or brightness/value (0-1) depending on which scheme (HSV/HSL) is being used.

@param [Fixnum] chroma The associated chroma value. @return [Array<Fixnum>] A scaled r,g,b triple. Scheme-dependent

adjustments are still needed to reach the true r,g,b values.

@see en.wikipedia.org/wiki/HSL_and_HSV @see www.tomjewett.com/colors/hsb.html @private

    # File lib/chunky_png/color.rb
249 def cylindrical_to_cubic(hue, saturation, y_component, chroma)
250   hue_prime = hue.fdiv(60)
251   x = chroma * (1 - (hue_prime % 2 - 1).abs)
252 
253   case hue_prime
254   when (0...1); [chroma, x, 0]
255   when (1...2); [x, chroma, 0]
256   when (2...3); [0, chroma, x]
257   when (3...4); [0, x, chroma]
258   when (4...5); [x, 0, chroma]
259   when (5..6);  [chroma, 0, x]
260   end
261 end
hue_and_chroma(color) click to toggle source

This method encapsulates the logic needed to extract hue and chroma from a ChunkPNG color. This logic is shared by the cylindrical HSV/HSB and HSL color space models.

@param [Integer] A ChunkyPNG color. @return [Fixnum] hue The hue of the color (0-360) @return [Fixnum] chroma The chroma of the color (0-1) @return [Fixnum] max The magnitude of the largest scaled rgb component (0-1) @return [Fixnum] min The magnitude of the smallest scaled rgb component (0-1) @private

    # File lib/chunky_png/color.rb
638 def hue_and_chroma(color)
639   scaled_rgb      = to_truecolor_bytes(color)
640   scaled_rgb.map! { |component| component.fdiv(255) }
641   min, max = scaled_rgb.minmax
642   chroma   = max - min
643 
644   r, g, b   = scaled_rgb
645   hue_prime = chroma.zero? ? 0 : case max
646                                  when r; (g - b).fdiv(chroma)
647                                  when g; (b - r).fdiv(chroma) + 2
648                                  when b; (r - g).fdiv(chroma) + 4
649                                  else 0
650                                  end
651   hue = 60 * hue_prime
652 
653   return hue.round, chroma, max, min
654 end