How do I convert RGB to HEX color?
You can convert RGB to HEX code as follows:
- Write down the RGB values: three integers between 0 and 255, representing red, green, and blue, respectively.
- Convert each of them into a hexadecimal number.
- We need two-digit hexadecimal numbers. If need be, add a leading zero:
04for4, or0AforA. - Combine the three hex digits into one string and adorn it with the hash # prefix. RGB to HEX color conversion is ready!
How do I convert RGB to HEX by hand?
What's the difference between RGB and HEX?
Just split the string up, and then use rgb:
x <- c("165 239 210", "111 45 93")
sapply(strsplit(x, " "), function(x)
rgb(x[1], x[2], x[3], maxColorValue=255))
#[1] "#A5EFD2" "#6F2D5D"
This answer is based off the answer to this same question by Hong Ooi but instead defines a function rgb2col function that takes as input a matrix of rgb values of the form returned by col2rgb. This means we can convert from hex to rgb and back again with just these two functions.
In other words, rgb2col(col2rgb(x)) = col2rgb(rgb2col(x)) = x.
Input structure
Start with a matrix of RGB colors of the form returned by col2rgb(). For example:
[,1] [,2]
red 213 0
green 94 158
blue 0 115
Function
This function will convert the matrix to a vector of hex colors.
rgb2col = function(rgbmat){
# function to apply to each column of input rgbmat
ProcessColumn = function(col){
rgb(rgbmat[1, col],
rgbmat[2, col],
rgbmat[3, col],
maxColorValue = 255)
}
# Apply the function
sapply(1:ncol(rgbmat), ProcessColumn)
}
Example use case
You might want to modify a color palette manually but not feel as comfortable working with hex numbers. For example, suppose I want to darken a vector of two colors a little.
# Colors to darken
ColorsHex = c("#D55E00","#009E73")
# Convert to rgb
# This is the step where we get the matrix
ColorsRGB = col2rgb(ColorsHex)
# Darken colors by lowering values of RGB
ColorsRGBDark = round(ColorsRGB*.7)
# Convert back to hex
ColorsHexDark = rgb2col(ColorsRGBDark)