将十六进制转换为RGBA


86

我的小提琴-http: //jsbin.com/pitu/1/edit

我想尝试将十六进制轻松转换为rgba。我曾经使用过的浏览器会默认使用rgb渲染颜色,因此,在使用Farbastastic颜色选择器时,我会通过抓住十六进制值生成的背景色将十六进制值转换为rgb(默认情况下rgb =简单转换)

我尝试将)符号替换为, 1),但这没有用,所以我去看看如何将rgb转换为rgba还是可行的,但是我仍然遇到麻烦。

jQuery的

$('.torgb').val($('#color').css('background-color'));
$('.torgba').val().replace(/rgb/g,"rgba");

目标
在此处输入图片说明

编辑

TinyColor是一个很棒的颜色处理js库,可以完成我在这里想要的一切。我想你们可能想尝试一下!- https://github.com/bgrins/TinyColor


1
TinyColor是一个很棒的颜色处理js库,可以完成我在这里想要的一切。我想你们可能想尝试一下!
Michael Schwartz

Answers:


155
//If you write your own code, remember hex color shortcuts (eg., #fff, #000)

function hexToRgbA(hex){
    var c;
    if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
        c= hex.substring(1).split('');
        if(c.length== 3){
            c= [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c= '0x'+c.join('');
        return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';
    }
    throw new Error('Bad Hex');
}

hexToRgbA('#fbafff')

/*  returned value: (String)
rgba(251,175,255,1)
*/

1
谢谢..像奇迹一样工作.. :)
Manprit Singh Sahota'May 25''17

4
很容易理解的解决方案,但它不支持8进制十六进制格式#ff0000aa
supersan

1
如果输入的字符不完全是3个或6个字符,则此方法不起作用。
Kehlan Krumme

93

@ ElDoRado1239有一个正确的想法,但还有一种更干净的方法:

function hexToRGB(hex, alpha) {
    var r = parseInt(hex.slice(1, 3), 16),
        g = parseInt(hex.slice(3, 5), 16),
        b = parseInt(hex.slice(5, 7), 16);

    if (alpha) {
        return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
    } else {
        return "rgb(" + r + ", " + g + ", " + b + ")";
    }
}

hexToRGB('#FF0000', 0.5);


1
注意:这将在十六进制快捷方式上失败,例如#fff。那应该很容易解决!
马修·赫伯斯特

1
好吧,是的,您必须为函数提供正确的输入…
AJFarkas

可读性强,我比基于reg exp的解决方案更喜欢它。
dahrens

做得好!我有话要说。我在字符串中的逗号和RGBA值之间保持空格有一些不好的经验。(例如:rgba(255,35,234,0.5))。特别是如果将此值传递给另一个程序,请注意这一点。因为有些程序不接受字符串值之间的空格。因此,最好从最终输出中删除那些空格。
Tharanga

eslint只是样式强制。只是偶然的,我没有写任何东西与您的风格偏好相抵触。实际上,例如,这不会影响我当前正在从事的项目。
AJFarkas

33

ES6函数仅处理带有或不带有'#'的6个字符的十六进制:

const hex2rgba = (hex, alpha = 1) => {
  const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  return `rgba(${r},${g},${b},${alpha})`;
};

用法:

hex2rgba('#af087b', .5)   // returns: rgba(175,8,123,0.5)
hex2rgba('af087b', .5)    // returns: rgba(175,8,123,0.5)
hex2rgba('af087b')        // returns: rgba(175,8,123,1)

由于toStringonArray与join,和事实输入可以是rrggbbaa hexconst rgb = hex.match(...)。slice(0,3).map(...)returnn` $ {rgb},$ {alpha }`;
Morteza Tourani

1
下面的代码还将转换hex2rgba('#369',0.5); var hex2rgba =(hex,alpha = 1)=> {const [r,g,b] = hex.match(hex.length <= 4?/ \ w / g:/ \ w \ w / g).map( x => parseInt(x.length <2?${x}${x}:x,16)); 回报rgba(${r},${g},${b},${alpha}); };
Serkan KONAKCI

14

干净的TypeScript版本:

hexToRGB(hex: string, alpha: string) {

  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);

  if (alpha) {
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
  } else {
    return `rgba(${r}, ${g}, ${b})`;
  }
}

基于@AJFarkas的答案。


1
在某些情况下,这并非每次都起作用,它会返回r,g或/和b的NaN。
重生

为我努力!Thx
萨克斯风演奏家

10

任何十六进制形式的模块化方法

主要挑战是,截至2018年,HEX的形式多种多样。传统格式为6个字符,缩写为3个字符,以及包含alpha的新的4和8个字符。以下函数可以处理任何十六进制格式。

const isValidHex = (hex) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hex)

const getChunksFromString = (st, chunkSize) => st.match(new RegExp(`.{${chunkSize}}`, "g"))

const convertHexUnitTo256 = (hexStr) => parseInt(hexStr.repeat(2 / hexStr.length), 16)

const getAlphafloat = (a, alpha) => {
    if (typeof a !== "undefined") {return a / 255}
    if ((typeof alpha != "number") || alpha <0 || alpha >1){
      return 1
    }
    return alpha
}

export const hexToRGBA = (hex, alpha) => {
    if (!isValidHex(hex)) {throw new Error("Invalid HEX")}
    const chunkSize = Math.floor((hex.length - 1) / 3)
    const hexArr = getChunksFromString(hex.slice(1), chunkSize)
    const [r, g, b, a] = hexArr.map(convertHexUnitTo256)
    return `rgba(${r}, ${g}, ${b}, ${getAlphafloat(a, alpha)})`
}

可以通过以下方式向功能提供Alpha:

  1. 作为4或8形式HEX的一部分。
  2. 作为0-1之间的第二个参数,

输出

    const c1 = "#f80"
    const c2 = "#f808"
    const c3 = "#0088ff"
    const c4 = "#0088ff88"
    const c5 = "#98736"

    console.log(hexToRGBA(c1))   //  rgba(255, 136, 0, 1)
    console.log(hexToRGBA(c2))   //  rgba(255, 136, 0, 0.53125)
    console.log(hexToRGBA(c3))   //  rgba(0, 136, 255, 1)
    console.log(hexToRGBA(c4))   //  rgba(0, 136, 255, 0.53125)
    console.log(hexToRGBA(c5))   //  Uncaught Error: Invalid HEX

    console.log(hexToRGBA(c1, 0.5))   //  rgba(255, 136, 0, 0.5)
    console.log(hexToRGBA(c3, 0.5))   //  rgba(0, 136, 255, 0.5)

1
某些浏览器支持不透明的十六进制颜色,而其他浏览器不支持。在将8形式的十六进制转换为rgba时,此答案非常有用,所有浏览器均支持rgba。
乔治,

1
@乔治,谢谢!创建完这个之后,我问自己是否真的需要这种综合方法。您的反馈很有价值。
本·卡尔普

1
我认为Alpha Calc中可能有1个小错误。我认为它应该显示为:返回/ 255,否则FF不会返回1
Dustin Kerstein

@DustinKerstein不错!可能不会造成伤害,但仍应修复。
Ben Carp

1
这是最好的答案,它适用于所有单元测试。
Menai Ala Eddine-阿拉丁

9

如果要将十六进制转换为rgba,则可以使用此功能,

function hex2rgba_convert(hex,opacity){
 hex = hex.replace('#','');
 r = parseInt(hex.substring(0, hex.length/3), 16);
 g = parseInt(hex.substring(hex.length/3, 2*hex.length/3), 16);
 b = parseInt(hex.substring(2*hex.length/3, 3*hex.length/3), 16);

 result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
 return result;
}

这是细节到rgba的十六进制


8

如果您提供Alpha,这是一个返回rgb或rgba的函数。该功能也可以转换短十六进制颜色代码。

功能:

function hexToRgb(hex, alpha) {
   hex   = hex.replace('#', '');
   var r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16);
   var g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16);
   var b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16);
   if ( alpha ) {
      return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')';
   }
   else {
      return 'rgb(' + r + ', ' + g + ', ' + b + ')';
   }
}

例子:

hexToRgb('FF0000');// rgb(255, 0, 0)
hexToRgb('#FF0000');// rgb(255, 0, 0)
hexToRgb('#FF0000', 1);// rgba(255, 0, 0, 1)
hexToRgb('F00');// rgb(255, 0, 0)
hexToRgb('#F00');// rgb(255, 0, 0)
hexToRgb('#F00', 1);// rgba(255, 0, 0, 1)

6

ES6现代版,免费RegEx,具有错误检查和恒定箭头功能的解决方案,对于错误返回null。如果未提供alpha,则使用默认值1:

const hexToRGB = (hex, alpha = 1) => {
    let parseString = hex;
    if (hex.startsWith('#')) {parseString = hex.slice(1, 7);}
    if (parseString.length !== 6) {return null;}
    const r = parseInt(parseString.slice(0, 2), 16);
    const g = parseInt(parseString.slice(2, 4), 16);
    const b = parseInt(parseString.slice(4, 6), 16);
    if (isNaN(r) || isNaN(g) || isNaN(b)) {return null;}
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};

注意:返回null错误。您可以{return null;}用throw语句:代替{throw "Not a valid hex color!";},但是随后您应该在内部调用它 try-catch

hexToRGB("#3454r5") => null
hexToRGB("#345465") => rgba(52, 84, 101, 1)
hexToRGB("#345465", 0.5) => rgba(52, 84, 101, 0.5)

5

纯JS解决方案是否有帮助:

function hexToRGB(hex,alphaYes){
 var h = "0123456789ABCDEF";
 var r = h.indexOf(hex[1])*16+h.indexOf(hex[2]);
 var g = h.indexOf(hex[3])*16+h.indexOf(hex[4]);
 var b = h.indexOf(hex[5])*16+h.indexOf(hex[6]);
 if(alphaYes) return "rgba("+r+", "+g+", "+b+", 1)";
 else return "rgb("+r+", "+g+", "+b+")";
}

“ alphaYes”是“ true”还是“ false”,具体取决于您是否要使用alpha。

预习


else关键字是在这种情况下是不必要的。无论如何,它将返回非字母。
安迪

哦,是的,但这对我来说似乎更“整洁”。我猜只是个人喜好。
ElDoRado1239

此代码不适用于小写的十六进制(例如#f0a16e)。我建议转换hextoUpperCase第一次。
philippe_b

3

我喜欢@AJFarkas答案,并在其中添加了对快捷方式十六进制(#fff)的支持

function hexToRGB(hex, alpha) {
    if (!hex || [4, 7].indexOf(hex.length) === -1) {
        return; // throw new Error('Bad Hex');
    }

    hex = hex.substr(1);
    // if shortcuts (#F00) -> set to normal (#FF0000)
    if (hex.length === 3) { 
        hex = hex.split('').map(function(el){ 
              return el + el + '';
            }).join('');
    }

    var r = parseInt(hex.slice(0, 2), 16),
        g = parseInt(hex.slice(2, 4), 16),
        b = parseInt(hex.slice(4, 6), 16);

    if (alpha !== undefined) {
        return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
    } else {
        return "rgb(" + r + ", " + g + ", " + b + ")";
    }
}

document.write(hexToRGB('#FF0000', 0.5));
document.write('<br>');
document.write(hexToRGB('#F00', 0.4));


3

这是ES2015 +版本,该版本更具防御性,可以处理速记3位数语法。

/*
 * Takes a 3 or 6-digit hex color code, and an optional 0-255 numeric alpha value
 */
function hexToRGB(hex, alpha) {
  if (typeof hex !== 'string' || hex[0] !== '#') return null; // or return 'transparent'

  const stringValues = (hex.length === 4)
        ? [hex.slice(1, 2), hex.slice(2, 3), hex.slice(3, 4)].map(n => `${n}${n}`)
        : [hex.slice(1, 3), hex.slice(3, 5), hex.slice(5, 7)];
  const intValues = stringValues.map(n => parseInt(n, 16));

  return (typeof alpha === 'number')
    ? `rgba(${intValues.join(', ')}, ${alpha})`
    : `rgb(${intValues.join(', ')})`;
}

1

另一个基于位移。

// hex can be a string in the format of "fc9a04", "0xfc9a04" or "#fc90a4" (uppercase digits are allowed) or the equivalent number
// alpha should be 0-1
const hex2rgb = (hex, alpha) => {
  const c = typeof(hex) === 'string' ? parseInt(hex.replace('#', ''), 16)  : hex;
  return `rgb(${c >> 16}, ${(c & 0xff00) >> 8}, ${c & 0xff}, ${alpha})`;
};

1

尝试

// hex - str e.g. "#abcdef"; a - alpha range 0-1; result e.g. "rgba(1,1,1,0)"
let hex2rgba= (hex,a)=> `rgb(${hex.substr(1).match(/../g).map(x=>+`0x${x}`)},${a})`


0

将带有alpha(ahex)的十六进制转换为rgba。

function ahex_to_rba(ahex) {
    //clean #
    ahex = ahex.substring(1, ahex.length);
    ahex = ahex.split('');

    var r = ahex[0] + ahex[0],
        g = ahex[1] + ahex[1],
        b = ahex[2] + ahex[2],
        a = ahex[3] + ahex[3];

    if (ahex.length >= 6) {
        r = ahex[0] + ahex[1];
        g = ahex[2] + ahex[3];
        b = ahex[4] + ahex[5];
        a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]);
    }

    var int_r = parseInt(r, 16),
        int_g = parseInt(g, 16),
        int_b = parseInt(b, 16),
        int_a = parseInt(a, 16);


    int_a = int_a / 255;

    if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2);

    if (int_a || int_a === 0)
        return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')';
    return 'rgb('+int_r+', '+int_g+', '+int_b+')';
}

自己尝试一下代码段:

原作者


0

添加到@ ElDoRado1239

对于那些想要传递Alpha值的用户(打字稿片段):

static hexToRGB(hex: string, alpha: number): string {
    var h = "0123456789ABCDEF";
    var r = h.indexOf(hex[1]) * 16 + h.indexOf(hex[2]);
    var g = h.indexOf(hex[3]) * 16 + h.indexOf(hex[4]);
    var b = h.indexOf(hex[5]) * 16 + h.indexOf(hex[6]);
    if (alpha) {
      return `rgba(${r}, ${g}, ${b}, ${alpha})`
    }

    return `rgba(${r}, ${g}, ${b})`;
  }


-9

试试这个

<div class="torgb" onclick="rgba();" style="background-color:#000; width:20px; height:20px;"></div>
<script>
function rgba(){
$('.torgb').attr('background-color','rgba(0,0,0,1)');
$('.torgb').attr('onclick','hex();');
}
function hex(){
$('.torgb').attr('background-color','#000');
$('.torgb').attr('onclick','rgba();');
}
</script>

哪里都是hexrgba功能是从哪里来的?
安迪
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.