juanmah
juanmah

Reputation: 1189

R Hex to RGB converter

Suppose I have this color in HEX values (including alpha):

x <- "#FF2400FF"

Is there a neat package to convert HEX values to RGB values in R? Or a simple bit of code to do that?

[#1] c("36 0 255")

Edit: This is the opposite way of RGB to Hex converter question

Upvotes: 9

Views: 13129

Answers (4)

Abel Callejo
Abel Callejo

Reputation: 14919

Example 1

You can get the RGB values as a 1-dimensional array

hex.rgba.color <- "#FF2400FF"
rgb.array <- col2rgb( hex.rgba.color )
print( rgb.array )

Output

      [,1]
red    255
green   36
blue     0

Example 2

You can get the red, green, and blue values respectively as integers

hex.rgba.color <- "#FF2400FF"
rgb.array <- col2rgb( hex.rgba.color )
message( rgb.array[1] ) # red
message( rgb.array[2] ) # green
message( rgb.array[3] ) # blue

Output

255
36
0

Example 3

You can also get the alpha value as integer by simply adding alpha=TRUE

hex.rgba.color <- "#FF2400FF"
rgba.array <- col2rgb( hex.rgba.color, alpha=TRUE )
message( rgba.array[1] ) # red
message( rgba.array[2] ) # green
message( rgba.array[3] ) # blue
message( rgba.array[4] ) # alpha

Output

255
36
0
255

Example 4

You can get all the values as vector by typecasting the array with as.vector()

hex.rgba.color <- "#FF2400FF"
rgba.vector <- as.vector( col2rgb( hex.rgba.color, alpha=TRUE ) )
print( rgba.vector )

Output

[1] 255  36   0 255

Upvotes: 3

juanmah
juanmah

Reputation: 1189

As @Cath commented, it exists a function to do that:

col2rgb(heat.colors(10))

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
red    255  255  255  255  255  255  255  255  255   255
green    0   36   73  109  146  182  219  255  255   255
blue     0    0    0    0    0    0    0    0   64   191

Upvotes: 0

Daniel
Daniel

Reputation: 7832

Based on the comments already given, you can use this code:

x <- "#FF2400FF"
paste(as.vector(col2rgb(x)), collapse = " ")
#> [1] "255 36 0"

However, looking at your requested result, it seems that you have the alpha-value as first hex-number in your x - so you need to create a substring:

x <- "#FF2400FF"
paste(as.vector(col2rgb(paste0("#", substr(x, 4, 10)))), collapse = " ")
#> [1] "36 0 255"

Upvotes: 13

juanmah
juanmah

Reputation: 1189

With this code, HEX colors strings are splitted and converted to integers:

for (color in heat.colors(10)) {
  hex_splitted_color = c(paste('0x', substr(color, 4, 5), sep = ''),
                         paste('0x', substr(color, 6, 7), sep = ''),
                         paste('0x', substr(color, 8, 9), sep = ''))
  print(strtoi(hex_splitted_color))
}
[1]   0   0 255
[1]  36   0 255
[1]  73   0 255
[1] 109   0 255
[1] 146   0 255
[1] 182   0 255
[1] 219   0 255
[1] 255   0 255
[1] 255  64 255
[1] 255 191 255

Upvotes: 0

Related Questions