如何将RGB格式的颜色转换为十六进制格式,或将十六进制格式的颜色转换为RGB格式?
例如,将'#0080C0'
转换为 (0, 128, 192)
。
如何将RGB格式的颜色转换为十六进制格式,或将十六进制格式的颜色转换为RGB格式?
例如,将'#0080C0'
转换为 (0, 128, 192)
。
哇,这些答案都没有处理分数等边缘情况。而且当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');
}
}
rgbToHex = (rgb) ->
a = rgb.match /\d+/g
rgb unless a.length is 3
"##{ ((1 << 24) + (parseInt(a[0]) << 16) + (parseInt(a[1]) << 8) + parseInt(a[2])).toString(16).slice(1) }"
非常简单的一行代码。通过逗号拆分RGB,忽略非数字字符,转换为十六进制,填充0,并以井号结束。
var yellow = 'rgb(255, 255, 0)';
var rgb2hex = str => "#"+str.split(',').map(s => (s.replace(/\D/g,'')|0).toString(16)).map(s => s.length < 2 ? "0"+s : s).join('');
console.log(rgb2hex(yellow));
使用组合匿名函数和Array.map
可以使代码更加简洁、流畅。
var write=function(str){document.body.innerHTML=JSON.stringify(str,null,' ');};
function hexToRgb(hex, asObj) {
return (function(res) {
return res == null ? null : (function(parts) {
return !asObj ? parts : { r : parts[0], g : parts[1], b : parts[2] }
}(res.slice(1,4).map(function(val) { return parseInt(val, 16); })));
}(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)));
}
function rgbToHex(r, g, b) {
return (function(values) {
return '#' + values.map(function(intVal) {
return (function(hexVal) {
return hexVal.length == 1 ? "0" + hexVal : hexVal;
}(intVal.toString(16)));
}).join('');
}(arguments.length === 1 ? Array.isArray(r) ? r : [r.r, r.g, r.b] : [r, g, b]))
}
// Prints: { r: 255, g: 127, b: 92 }
write(hexToRgb(rgbToHex(hexToRgb(rgbToHex(255, 127, 92), true)), true));
body{font-family:monospace;white-space:pre}
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
const hexToRgb = (hex) => {
// Remove the # character if present
hex = hex.replace("#", "");
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
if (hex.length === 3) {
hex = hex.replace(/(.)/g, "$1$1");
}
// Verify if the input is a valid hexadecimal color code
const validHexRegex = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
if (!validHexRegex.test(hex)) {
throw new Error("Invalid Hexadecimal Color Code.");
}
// Convert the hex value to decimal
const [r, g, b] = hex.match(/[A-Fa-f0-9]{2}/g).map((value) => parseInt(value, 16));
// Return the RGB values as an object
return {
r,
g,
b
};
};
// Example usage
const hexCode = "#FF0000";
const rgb = hexToRgb(hexCode);
console.log(rgb); // { r: 255, g: 0, b: 0 }
适用于那些看重短箭头函数的用户。
David's Answer的箭头函数版本。
const hex2rgb = h => [(x=parseInt(h,16)) >> 16 & 255,x >> 8 & 255, x & 255];
#
。const hex2rgb = h => {
if(h[0] == '#') {h = h.slice(1)};
if(h.length <= 3) {h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2]};
h = parseInt(h,16);
return [h >> 16 & 255,h >> 8 & 255, h & 255];
};
const rgb2hex = (r,g,b) => ((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);
npx
,可以运行npx create-react-app hex-to-rgb
。import React, { Component, Fragment } from 'react';
const styles = {
display: 'block',
margin: '20px auto',
input: {
width: 170,
},
button: {
margin: '0 auto'
}
}
// test case 1
// #f0f
// test case 2
// #ff00ff
class HexToRGBColorConverter extends Component {
state = {
result: false,
color: "#ff00ff",
}
hexToRgb = color => {
let container = [[], [], []];
// check for shorthand hax string
if (color.length >= 3) {
// remove hash from string
// convert string to array
color = color.substring(1).split("");
for (let key = 0; key < color.length; key++) {
let value = color[key];
container[2].push(value);
// if the length is 3 we
// we need to add the value
// to the index we just updated
if (color.length === 3) container[2][key] += value;
}
for (let index = 0; index < color.length; index++) {
let isEven = index % 2 === 0;
// If index is odd an number
// push the value into the first
// index in our container
if (isEven) container[0].push(color[index]);
// If index is even an number
if (!isEven) {
// again, push the value into the
// first index in the container
container[0] += color[index];
// Push the containers first index
// into the second index of the container
container[1].push(container[0]);
// Flush the first index of
// of the container
// before starting a new set
container[0] = [];
}
}
// Check container length
if (container.length === 3) {
// Remove only one element of the array
// Starting at the array's first index
container.splice(0, 1);
let values = container[color.length % 2];
return {
r: parseInt(values[0], 16),
g: parseInt(values[1], 16),
b: parseInt(values[2], 16)
}
}
}
return false;
}
handleOnClick = event => {
event.preventDefault();
const { color } = this.state;
const state = Object.assign({}, this.state);
state.result = this.hexToRgb(color);
this.setState(state);
}
handleOnChange = event => {
event.preventDefault();
const { value } = event.currentTarget;
const pattern = /^([a-zA-Z0-9])/;
const boundaries = [3, 6];
if (
pattern.test(value) &&
boundaries.includes(value.length)
) {
const state = Object.assign({}, this.state);
state.color = `#${value}`;
this.setState(state);
}
}
render() {
const { color, result } = this.state;
console.log('this.state ', color, result);
return (
<Fragment>
<input
type="text"
onChange={this.handleOnChange}
style={{ ...styles, ...styles.input }} />
<button
onClick={this.handleOnClick}
style={{ ...styles, ...styles.button }}>
Convert hex to rgba
</button>
{
!!result &&
<div style={{ textAlign: 'center' }}>
Converted { color } to { JSON.stringify(result) }
</div>
}
</Fragment>
)
}
}
export default App;
编程愉快 =)
list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;
这将返回123,222,132
对于RGB到HEX的转换
$rgb = (123,222,132),
$rgbarr = explode(",",$rgb,3);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);
这将返回 #7bde84
"30,209,19"
)转换为相应的十六进制字符串"#1ed113"
:var rgb = '30,209,19';
var hex = _.reduce(rgb.split(','), function(hexAccumulator, rgbValue) {
var intColor = _.parseInt(rgbValue);
if (_.isNaN(intColor)) {
throw new Error('The value ' + rgbValue + ' was not able to be converted to int');
}
// Ensure a value such as 2 is converted to "02".
var hexColor = _.padLeft(intColor.toString(16), 2, '0');
return hexAccumulator + hexColor;
}, '#');