16 진수를 RGBA로 변환


86

내 바이올린-http: //jsbin.com/pitu/1/edit

나는 쉬운 hex to rgba 변환을 시도하고 싶었습니다. 내가 사용한 적이있는 브라우저는 rgb를 기본값으로 사용하여 색상을 렌더링하므로 극단적 인 색상 선택기를 사용할 때 16 진수 값이 생성하는 배경 색상을 잡아서 16 진수 값을 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

답변:


160
//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 싱 호타에게

4
매우 이해하기 쉬운 솔루션이지만 8 형 16 진수를 지원하지 않습니다 #ff0000aa.
supersan

1
입력이 정확히 3 자 또는 6자가 아닌 경우 작동하지 않습니다.
Kehlan Krumme

97

@ 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
참고 : HEX 바로 가기 (예 : #fff. 그래도 쉽게 고칠 수 있습니다!
Matthew Herbst

1
음, 그래, 당신은 ... 기능에게 올바른 입력을 제공해야
AJFarkas

매우 읽기 쉽고 reg exp 기반 솔루션보다 훨씬 더 좋아합니다.
dahrens

잘 했어!! 그래도 언급해야 할 사항이 있습니다. 문자열에서 쉼표와 RGBA 값 사이에 공백을 유지하는 나쁜 경험이 있습니다. (예 : rgba (255, 35, 234, 0.5)). 특히이 값을 다른 프로그램에 전달하는 경우이를 염두에 두십시오. 문자열의 값 사이에 공백을 허용하지 않는 일부 프로그램이 있기 때문입니다. 따라서 최종 출력에서 ​​이러한 공백을 제거하는 것이 좋습니다.
Tharanga

eslint스타일 집행 일뿐입니다. 내가 쓴 어떤 것도 당신의 스타일 선호도와 모순되는 것은 우연한 일입니다. 사실 이것은 예를 들어 현재 작업중인 프로젝트에서 linting을 통과하지 못할 것입니다.
AJFarkas

34

'#'이 있거나없는 6 자 16 진수 만 처리하는 ES6 함수 :

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)

이후 toStringArray조인 ,하고 사실 입력이 될 수 rrggbbaa hex있습니다 (...) const를 RGB = hex.match로 변경할 수 있습니다. 조각 (0.3) .MAP (...) returnn` $ {RGB}, $ {알파 }`;
Morteza Tourani 2019 년

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

17

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 `rgb(${r}, ${g}, ${b})`;
  }
}

@AJFarkas의 답변을 기반으로합니다.


1
이것은 경우에 따라 r, g 또는 / 및 b에 대해 NaN을 반환 할 때마다 작동하지 않습니다.
Renascent 2019-04-30

나를 위해 운동했습니다! Thx
Saxophonist

rgb(${r}, ${g}, ${b})알파가 없기 때문에 else 반환 하지 않습니까?
Amanshu Kataria 20.11.30

@AmanshuKataria 예, 그래야합니다. 좋은 자리.
Chrillewoodz

10

모든 16 진 형태 모듈 방식

주요 과제는 2018 년 현재 몇 가지 형태의 HEX가 있다는 것입니다. 6 자 전통 형식, 3 자 단축 형식, 알파를 포함하는 새로운 4 자 및 8 자 형식. 다음 함수는 모든 HEX 형식을 처리 할 수 ​​있습니다.

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
일부 브라우저는 불투명도가있는 16 진수 색상을 지원하고 다른 브라우저는 지원하지 않습니다. 이 답변은 8 형식 16 진수를 rgba로 변환하는 데 매우 유용했으며 rgba는 모든 브라우저에서 지원됩니다.
George

1
@ 조지, 감사합니다! 이것을 만든 후 나는 그러한 포괄적 인 접근이 실제로 필요한지 스스로에게 물었다. 귀하의 의견은 소중합니다.
Ben Carp

1
알파 계산에 작은 버그가 하나있을 수 있다고 생각합니다. 나는 그것을 읽어야 생각하십시오 반환 / 255 그렇지 않으면 FF는 1 반환하지 않습니다
더스틴 Kerstein가

@DustinKerstein 좋은 캐치! 아마 해를 끼칠 수는 없지만 여전히 수정해야합니다.
Ben Carp

1
이것이 가장 좋은 대답이며 모든 단위 테스트에서 저에게 효과적이었습니다.
Menai Ala Eddine-Aladdin 20. 9.

8

다음은 알파를 제공하면 rgb 또는 rgba를 반환하는 함수입니다. 이 함수는 또한 짧은 16 진수 색상 코드도 변환합니다.

함수:

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"입니다.

시사


else키워드는이 경우에 필요하지 않습니다. 상관없이 비 알파를 반환합니다.
Andy

아, 그래,하지만이게 더 "정돈"된 것 같아. 개인적인 취향의 문제라고 생각합니다.
ElDoRado1239 2014

이 코드는 소문자 16 진수 (예 :)에서는 작동하지 않습니다 #f0a16e. 먼저 변환 hex하는 것이 좋습니다 toUpperCase.
philippe_b

3

@AJFarkas 답변이 마음에 들었고 바로 가기 16 진수 (#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

다음은 좀 더 방어적이고 속기 3 자리 구문을 처리하는 ES2015 + 버전입니다.

/*
 * 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})`


1

다음은 3, 4, 6 및 8 개의 문자 색상 코드를 지원하는 빠른 기능입니다.

function hexToRGBA(hex) {
    // remove invalid characters
    hex = hex.replace(/[^0-9a-fA-F]/g, '');

    if (hex.length < 5) { 
        // 3, 4 characters double-up
        hex = hex.split('').map(s => s + s).join('');
    }

    // parse pairs of two
    let rgba = hex.match(/.{1,2}/g).map(s => parseInt(s, 16));

    // alpha code between 0 & 1 / default 1
    rgba[3] = rgba.length > 3 ? parseFloat(rgba[3] / 255).toFixed(2): 1;

    return 'rgba(' + rgba.join(', ') + ')';
}

이것이하는 일입니다. 16 진수가 아닌 문자를 제거합니다. HEX가 5 자 (3 또는 4)보다 짧으면 각 문자를 두 배로 늘립니다. 그런 다음 HEX를 두 문자 쌍으로 분할하고 각 쌍을 정수로 구문 분석합니다. 알파 HEX가 있으면 0에서 1까지의 부동 소수점으로 구문 분석되고, 그렇지 않으면 1로 기본 설정됩니다. RGBA 문자열은 배열을 결합하여 형성되고 반환됩니다.


0

알파 (ahex)가있는 HEX를 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에 추가

알파 값 (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})`;
  }


-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함수 는 어디 에서 오는가?
Andy
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.