ProgramingTip

16 진수를 RGBA로 변환

bestdevel 2020. 12. 2. 21:38
반응형

16 진수를 RGBA로 변환


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

나는 쉬운 hex to rgba 변환을 시도하고 싶었습니다. 내가 사용했던 브라우저는 rgb를 사용하여 사용하여 색상을 사용할 때 16 진수 값이 생성하는 배경색을 잡아서 16 진수 값을 생성하는 rgb로 변환합니다 (기본적으로 rgb = 단순 변환)

)를으로 기호 바꾸려고했지만 , 1)작동하지 않았으므로 RGB를 RGBA CHAPTER 2하는 방법로을 확인 하려고했는데 여전히 문제가 있습니다.

jquery

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

목표
여기에 이미지 설명 입력

편집 :

TinyColor내가 여기에서 원하는 모든 것을 수행하는 훌륭한 색상 조작 js 라이브러리입니다. 나는 너희들이 그것을 시도하고 싶을 생각한다! -https : //github.com/bgrins/TinyColor


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

@ 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);


'#'이없는 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)

16 진수를 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에 대한 16 진수입니다.


TypeScript 버전 정리 :

hexToRGB(hex, alpha) {

  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의 답변을 기반으로합니다.


다음은 알파를 제공하면 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)


ES6 모던, RegEx 무료, 오류 검사 및 상수 화살표 기능이있는 솔루션으로 오류에 대해 null을 반환합니다. 알파가 제공되지 않는 문서 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)

2018 년 12 월-모든 Hex Form Modular Approach

주요 과제는 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 / 256}
    if (typeof alpha !== "undefined"){
        if (1 < alpha && alpha <= 100) { return alpha / 100}
        if (0 <= alpha && alpha <= 1) { return alpha }
    }
    return 1
}

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

알파는 다음과 같은 방법으로 함수를 제공 할 수 있습니다.

  1. 4 또는 8 양식의 일부로 HEX.
  2. 0-1 사이의 두 번째 매개 변수로
  3. 1-100 사이의 두 번째 매개 변수로

많이

    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(c1, 50))   //  rgba(255, 136, 0, 0.5)
    console.log(hexToRGBA(c3, 0.5))   //  rgba(0, 136, 255, 0.5)
    console.log(hexToRGBA(c3, 50))   //  rgba(0, 136, 255, 0.5)
    console.log(hexToRGBA(c3, 120))   //  rgba(0, 136, 255, 1)

도움이되는 경우 순수 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"입니다.

시사


다음은 좀 더 방어적인 속기 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(', ')})`;
}

@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));


그리고 비트 시프 팅을 기반으로 한 또 다른 것.

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

이 시도

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

참고 URL : https://stackoverflow.com/questions/21646738/convert-hex-to-rgba

반응형