This is a version of grDevices::rgb() that works with the standard colour format used in farver (matrix or data.frame with colours in rows). It further support taking input from any colour space.

encode_colour(colour, alpha = NULL, from = "rgb", white = "D65")

Arguments

colour

A numeric matrix (or an object coercible to one) with colours encoded in the rows and the different colour space values in the columns. For all colourspaces except 'cmyk' this will mean a matrix with three columns - for 'cmyk' it means four columns.

alpha

A numeric vector between 0 and 1. Will be recycled to the number of rows in colour. If NULL or a single NA it will be ignored.

from

The input colour space. Allowed values are: "cmy", "cmyk", "hsl", "hsb", "hsv", "lab" (CIE L*ab), "hunterlab" (Hunter Lab), "oklab", "lch" (CIE Lch(ab) / polarLAB), "luv", "rgb" (sRGB), "xyz", "yxy" (CIE xyY), "hcl" (CIE Lch(uv) / polarLuv), or "oklch" (Polar form of oklab)

white

The white reference of the input colour space. Will only have an effect for relative colour spaces such as Lab and luv. Any value accepted by as_white_ref() allowed.

Value

A character vector with colours encoded as #RRGGBB(AA)

Note

The output may differ slightly from that of grDevices::rgb() since rgb() doesn't round numeric values correctly.

Handling of non-finite and out of bounds values

NA, NaN, -Inf, and Inf are treated as invalid input and will result in NA values for the colour. If a given colourspace has finite bounds in some of their channels, the input will be capped before conversion, and the output will be capped before returning, so that both input and output colours are valid colours in their respective space. This means that converting back and forth between two colourspaces may result in a change in the colour if the gamut of one of the spaces is less than the other.

See also

Other encoding and decoding functions: decode_colour(), manip_channel

Examples

spectrum <- decode_colour(rainbow(10))

encode_colour(spectrum)
#>  [1] "#FF0000" "#FF9900" "#CCFF00" "#33FF00" "#00FF66" "#00FFFF" "#0066FF"
#>  [8] "#3300FF" "#CC00FF" "#FF0099"

# Attach alpha values
encode_colour(spectrum, alpha = c(0.5, 1))
#>  [1] "#FF000080" "#FF9900"   "#CCFF0080" "#33FF00"   "#00FF6680" "#00FFFF"  
#>  [7] "#0066FF80" "#3300FF"   "#CC00FF80" "#FF0099"  

# Encode from a different colour space
spectrum_hcl <- convert_colour(spectrum, 'rgb', 'hcl')
encode_colour(spectrum_hcl, from = 'hcl')
#>  [1] "#FF0000" "#FF9900" "#CCFF00" "#33FF00" "#00FF66" "#00FFFF" "#0066FF"
#>  [8] "#3300FF" "#CC00FF" "#FF0099"