RGB转Hex转换器

20

假设我有这个向量

x <- c("165 239 210", "111 45 93")

在R中是否有一个方便的包可以将RGB值转换为十六进制值?我发现很多JavaScript的方法,但没有一个是针对R的。

x <- "#A5EFD2" "#6F2D5D"
4个回答

38

只需将字符串拆分,然后使用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"

对我来说,我是从 col2rgb 开始的,所以下面的简写方式可以使用(并且在这个例子中也类似):do.call(rgb, as.list(col2rgb('red')/255)) - MichaelChirico
仅供参考:在拆分字符串后,使用函数可以使其更加通用: rgb_2_hex <- function(r,g,b){rgb(r, g, b, maxColorValue = 255)} - aae

2
这个答案基于 Hong Ooi 的相同问题的答案,但是定义了一个名为rgb2col的函数,它将一个由col2rgb返回的rgb值矩阵作为输入。这意味着我们只需使用这两个函数就可以在十六进制和rgb之间进行转换。 换句话说:rgb2col(col2rgb(x))=col2rgb(rgb2col(x))=x

输入结构

col2rgb()返回的RGB颜色矩阵开始。例如:

      [,1] [,2]
red    213    0
green   94  158
blue     0  115

功能

此函数将把矩阵转换为十六进制颜色向量。

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)
}

使用案例示例

您可能希望手动修改调色板,但不太熟悉十六进制数字。例如,假设我想稍微加深两种颜色的向量。

# 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)

1
你可以将其转换为数字矩阵,然后使用colourvalues::convert_colours()
colourvalues::convert_colours( 
  matrix( as.numeric( unlist( strsplit(x, " ") ) ) , ncol = 3, byrow = T)
)
# [1] "#A5EFD2" "#6F2D5D"

-4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接