如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
建立了我自己的十六进制RGB转换器。我希望这能帮助到一些人。
我用react来做沙盒。
用法:
根据官方文档安装React,或者如果你全局安装了npx,运行npx create-react-app hexto -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;
快乐编码=)
其他回答
您可以尝试下面这段简单的代码。
用于十六进制到RGB
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
我正在使用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/
哇。这些答案都不能处理分数的边缘情况,等等。当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');
}
}
hexToRgb的另一个版本:
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
编辑:3/28/2017 这是另一种似乎更快的方法
function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);
return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}
编辑:8/11/2017 经过更多测试后,上面的新方法并没有更快:(。虽然这是一种有趣的替代方式。
一个简单的答案,将RGB转换为十六进制。这里颜色通道的值被限定在0到255之间。
function RGBToHex(r = 0, g = 0, b = 0) {
// clamp and convert to hex
let hr = Math.max(0, Math.min(255, Math.round(r))).toString(16);
let hg = Math.max(0, Math.min(255, Math.round(g))).toString(16);
let hb = Math.max(0, Math.min(255, Math.round(b))).toString(16);
return "#" +
(hr.length<2?"0":"") + hr +
(hg.length<2?"0":"") + hg +
(hb.length<2?"0":"") + hb;
}