如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
基于@ michazperzhaakowski的回答(EcmaScipt 6)和他基于Tim Down的回答的回答
我写了一个转换hexToRGB函数的修改版本,增加了安全检查r/g/b颜色组件是否在0-255之间,而且函数可以接受数字r/g/b参数或字符串r/g/b参数,如下所示:
function rgbToHex(r, g, b) {
r = Math.abs(r);
g = Math.abs(g);
b = Math.abs(b);
if ( r < 0 ) r = 0;
if ( g < 0 ) g = 0;
if ( b < 0 ) b = 0;
if ( r > 255 ) r = 255;
if ( g > 255 ) g = 255;
if ( b > 255 ) b = 255;
return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex
}).join('');
}
为了安全地使用这个函数——你应该检查传递的字符串是否是真正的rbg字符串颜色——例如,一个非常简单的检查可以是:
if( rgbStr.substring(0,3) === 'rgb' ) {
let rgbColors = JSON.parse(rgbStr.replace('rgb(', '[').replace(')', ']'))
rgbStr = this.rgbToHex(rgbColors[0], rgbColors[1], rgbColors[2]);
.....
}
其他回答
function getRGB(color){
if(color.length == 7){
var r = parseInt(color.substr(1,2),16);
var g = parseInt(color.substr(3,2),16);
var b = parseInt(color.substr(5,2),16);
return 'rgb('+r+','+g+','+b+')' ;
}
else
console.log('Enter correct value');
}
var a = getRGB('#f0f0f0');
if(!a){
a = 'Enter correct value';
}
a;
下面是将HEX颜色值分别更改为红色,绿色,蓝色的Javascript代码。
R = hexToR("#FFFFFF");
G = hexToG("#FFFFFF");
B = hexToB("#FFFFFF");
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
我为RGB和十六进制颜色做了一个小的Javascript颜色类,这个类还包括RGB和十六进制验证函数。我将代码作为一个片段添加到这个答案中。
var colorClass = function() { this.validateRgb = function(color) { return typeof color === 'object' && color.length === 3 && Math.min.apply(null, color) >= 0 && Math.max.apply(null, color) <= 255; }; this.validateHex = function(color) { return color.match(/^\#?(([0-9a-f]{3}){1,2})$/i); }; this.hexToRgb = function(color) { var hex = color.replace(/^\#/, ''); var length = hex.length; return [ parseInt(length === 6 ? hex['0'] + hex['1'] : hex['0'] + hex['0'], 16), parseInt(length === 6 ? hex['2'] + hex['3'] : hex['1'] + hex['1'], 16), parseInt(length === 6 ? hex['4'] + hex['5'] : hex['2'] + hex['2'], 16) ]; }; this.rgbToHex = function(color) { return '#' + ('0' + parseInt(color['0'], 10).toString(16)).slice(-2) + ('0' + parseInt(color['1'], 10).toString(16)).slice(-2) + ('0' + parseInt(color['2'], 10).toString(16)).slice(-2); }; }; var colors = new colorClass(); console.log(colors.hexToRgb('#FFFFFF'));// [255, 255, 255] console.log(colors.rgbToHex([255, 255, 255]));// #FFFFFF
哇。这些答案都不能处理分数的边缘情况,等等。当r, g, b为零时,位移版本也不起作用。
这是一个可以处理r g b是小数的版本。它对颜色之间的插值很有用,所以我也包括了这段代码。但它仍然不能处理r, g, b在0-255范围之外的情况
/**
* Operates with colors.
* @class Q.Colors
*/
Q.Color = {
/**
* Get a color somewhere between startColor and endColor
* @method toHex
* @static
* @param {String|Number} startColor
* @param {String|Number} endColor
* @param {String|Number} fraction
* @returns {String} a color as a hex string without '#' in front
*/
toHex: function (r, g, b) {
return [r, g, b].map(x => {
const hex = Math.round(x).toString(16)
return hex.length === 1 ? '0' + hex : hex
}).join('');
},
/**
* Get a color somewhere between startColor and endColor
* @method between
* @static
* @param {String|Number} startColor
* @param {String|Number} endColor
* @param {String|Number} fraction
* @returns {String} a color as a hex string without '#' in front
*/
between: function(startColor, endColor, fraction) {
if (typeof startColor === 'string') {
startColor = parseInt(startColor.replace('#', '0x'), 16);
}
if (typeof endColor === 'string') {
endColor = parseInt(endColor.replace('#', '0x'), 16);
}
var startRed = (startColor >> 16) & 0xFF;
var startGreen = (startColor >> 8) & 0xFF;
var startBlue = startColor & 0xFF;
var endRed = (endColor >> 16) & 0xFF;
var endGreen = (endColor >> 8) & 0xFF;
var endBlue = endColor & 0xFF;
var newRed = startRed + fraction * (endRed - startRed);
var newGreen = startGreen + fraction * (endGreen - startGreen);
var newBlue = startBlue + fraction * (endBlue - startBlue);
return Q.Color.toHex(newRed, newGreen, newBlue);
},
/**
* Sets a new theme-color on the window
* @method setWindowTheme
* @static
* @param {String} color in any CSS format, such as "#aabbcc"
* @return {String} the previous color
*/
setWindowTheme: function (color) {
var meta = document.querySelector('meta[name="theme-color"]');
var prevColor = null;
if (meta) {
prevColor = meta.getAttribute('content');
}
if (color) {
if (!meta) {
meta = document.createElement('meta');
meta.setAttribute('name', 'theme-color');
}
meta.setAttribute('content', color);
}
return prevColor;
},
/**
* Gets the current window theme color
* @method getWindowTheme
* @static
* @param {String} color in any CSS format, such as "#aabbcc"
* @return {String} the previous color
*/
getWindowTheme: function () {
var meta = document.querySelector('meta[name="theme-color"]');
return meta.getAttribute('content');
}
}
我正在使用XAML数据,具有十六进制格式的#AARRGGBB (Alpha,红色,绿色,蓝色)。利用上面的答案,以下是我的解决方案:
function hexToRgba(hex) {
var bigint, r, g, b, a;
//Remove # character
var re = /^#?/;
var aRgb = hex.replace(re, '');
bigint = parseInt(aRgb, 16);
//If in #FFF format
if (aRgb.length == 3) {
r = (bigint >> 4) & 255;
g = (bigint >> 2) & 255;
b = bigint & 255;
return "rgba(" + r + "," + g + "," + b + ",1)";
}
//If in #RRGGBB format
if (aRgb.length >= 6) {
r = (bigint >> 16) & 255;
g = (bigint >> 8) & 255;
b = bigint & 255;
var rgb = r + "," + g + "," + b;
//If in #AARRBBGG format
if (aRgb.length == 8) {
a = ((bigint >> 24) & 255) / 255;
return "rgba(" + rgb + "," + a.toFixed(1) + ")";
}
}
return "rgba(" + rgb + ",1)";
}
http://jsfiddle.net/kvLyscs3/