Skip to contents

Convert from common color inputs to specified output type, adding alpha transparency for output formats that support it (hexa, rgba).

Usage

color_conv(
  color,
  alpha = 1,
  from = c("guess", "col", "hex", "hexa", "hex3", "rgb", "rgba", "lab"),
  to = c("hexa", "hex", "rgba", "rgb", "lab", "hsv")
)

Arguments

color

A color in one of the input formats (see Details)

alpha

Alpha transparency (values <=1 converted to 0-255); ignored if color has alpha already

from, to

Input and output color spaces, see Details below.

Value

color in to format

Details

  • color: one of the R colours listed in grDevices::colors(), e.g., "red"

  • hex: hexadecimal string, e.g., "#FF0000"

  • hexa: hexadecimal string with alpha, e.g., "#FF0000FF"

  • hex3: abbreviated hexadecimal string, e.g., "#F00"

  • rgb: vector of red, green and blue values 0-255, e.g., c(255, 0, 0)

  • rgba: vector of red, green, blue and alpha values 0-255, e.g., c(255, 0, 0, 255)

  • lab: CIE-Lab color

  • hsv: vector of hue, saturation and value values (0-1), e.g., c(h=0, s = 1, v = 1)

See also

Other color: col2lab(), lab2rgb()

Examples

# different ways to input red
color_conv("red")
#> [1] "#ff0000ff"
color_conv("#FF0000")
#> [1] "#ff0000ff"
color_conv("#FF0000FF")
#> [1] "#ff0000ff"
color_conv(c(255,0,0))
#> [1] "#ff0000ff"
color_conv("rgb(255,0,0)") # you can use CSS-style text
#> [1] "#ff0000ff"
color_conv(c(255,0,0,255))
#> [1] "#ff0000ff"

# Lab must have names or use text format to be guessed
color_conv(c(l = 53.2, a = 80.1, b = 67.2)) 
#> [1] "#ff0000ff"
color_conv("lab(53.2,80.1,67.2)")
#> [1] "#ff0000ff"

# else, it will be guessed as rgb; fix by setting from explicitly
color_conv(c(53.2, 80.1, 67.2))
#> [1] "#355043ff"
color_conv(c(53.2, 80.1, 67.2), from = "lab")
#> [1] "#ff0000ff"

# add 50% alpha transparency to dodgerblue
color_conv("dodgerblue", alpha = 0.5, to = "rgba")
#> [1]  30 144 255 128