将十六进制转换为RGBA

134

我的小测试 - http://jsbin.com/pitu/1/edit

我想尝试一下简单的十六进制转换为RGBA。我使用的每个浏览器都默认使用RGB来渲染颜色,因此当使用farbtastic颜色选择器时,我通过获取背景色来生成十六进制值所产生的rgb值(默认=简单转换)来将十六进制值转换为RGB。

我曾试图将)符号替换为, 1),但没有成功,所以我想看看将RGB转换为RGBA会如何工作,但我仍然遇到了困难。

JQuery

$('.torgb').val($('#color').css('background-color'));
$('.torgba').val().replace(/rgb/g,"rgba");
目标是: enter image description here 编辑: TinyColor 是一个很棒的颜色操作 JS 库,它可以满足我所有需求并且更多。我想你们也许想试试!- https://github.com/bgrins/TinyColor

2
TinyColor 是一个非常棒的颜色操作 JS 库,它可以满足我在这里所需的一切以及更多。我想你们可能想要尝试一下! - Michael Schwartz
28个回答

0

这应该适用于所有的使用情况(短代码、长代码、带/不带字母)

hexToRGBA=q=>{
  q=q.replace('#', '')
  let l=q.length
  if(l!=3 && l!=4 && l!==6 && l!=8) return
  let red, green, blue, alpha, red_, green_, blue_, alpha_
  switch(l){
    case 3:
      red_     = q[0]+q[0]
      green_   = q[1]+q[1]
      blue_    = q[2]+q[2]
      alpha    = 255
    break
    case 4:
      red_     = q[0]+q[0]
      green_   = q[1]+q[1]
      blue_    = q[2]+q[2]
      alpha_   = q[3]+q[3]
      alpha    = +("0x"+alpha_)
    break
    case 6:
      red_     = q[0]+q[1]
      green_   = q[2]+q[3]
      blue_    = q[4]+q[5]
      alpha    = 255
    break
    case 8:
      red_     = q[0]+q[1]
      green_   = q[2]+q[3]
      blue_    = q[4]+q[5]
      alpha_   = q[6]+q[7]
      alpha    = +("0x"+alpha_)
    break
  }
  red    = +("0x"+red_)
  green  = +("0x"+green_)
  blue   = +("0x"+blue_)
  return [red, green, blue, alpha]
}

注:alpha 作为第4个元素返回,范围为0-255


0
function* chunks(array, size) {
    for (let i = 0; i < array.length; i += size) {
        yield array.slice(i, i + size);
    }
}

function hexToRgba(hex, opacity = 1) {
    const arr = hex.replace("#", "").split("");

    return [...chunks(arr, arr.length === 6 ? 2 : 1)].reduce(
        (accum, cv, index, array) => {
            const lastIndex = array.length - 1 === index;
            const int = parseInt(
                array.length === 2 ? cv.join("") : cv[0] + cv[0],
                16
            );

            return accum + int + (lastIndex ? `,${opacity})` : ",");
        },
        "rgba("
    );
}

console.log(hexToRgba("#eee", 1));


使用生成器和reduce函数。可以带或不带#

0

如果您只需要处理简单情况(即不处理像#fff这样的快捷方式),则可以使用一行代码:

"aabbcc".split(/(..)/).filter(c=>c).map(c => parseInt(c, 16))

0

回复 @ElDoRado1239 的评论

对于那些想要传递 alpha 值的人(typescript 代码片段):

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

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+')';
}

使用代码片段自行尝试:

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+')';
}


$(function() {
  $('#go').click(function() {
    $('p b').text(ahex_to_rba($('#hex').val()));
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="hex" type="text" value="#ffaaffaa">
<input id="go" type="button" value="Go">

<p>Result: <b></b></p>

原作者


-1

我就把这个放在这里:

(str, alpha) => {


    if(!/^#([A-Fa-f0-9]{3}){1,2}$/.test(str))
      throw new Error('Bad hex')


    let c = str.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}, ${alpha})`;

};

-1

有时重新设计一个轮子会让你的行程更加顺畅... - James Walker
1
这是轮子设计师会说的话.. :D - thisismydesign
不需要用大锤砸小坚果... - EMiDU

-11

试一下

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

“hex”和“rgba”函数来自哪里? - Andy

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