개발/javascript

[javascript] RGBA ↔ HEX 변환

smile-haha 2021. 1. 12. 13:30
반응형

  //rgba validation check
  function validRGBA(rgba) {
  	if(!rgba instanceof Array){
    	return false;
    }
    else if(rgba.length<3){
    	return false;
    }
    //red value validation check
    else if(!(reba[0]&&reba[0]>=0 && reba[0]<=255)){
    	return false;
    }
    //green value validation check
    else if(!(reba[1]&&reba[1]>=0 && reba[1]<=255)){
    	return false;
    }
    //blue value validation check
    else if(!(reba[2]&&reba[2]>=0 && reba[2]<=255)){
    	return false;
    }
    
    //alpha value validation check
    if(reba[3]&&!(&&reba[3]>=0 && reba[3]<=1)){
    	return false;
    }
	return true;
  }
 
 //RGBA → HEX
 function RGBA2HEX(rgba) {
 	if(!validRGBA(rgba)){
    	throw new Error(`'${rgba}'is not rgba format!`);
    }
    let hex = '';
    rgba.slice(0, 3).forEach((c, index) => {
      hex +=
        parseInt(c).toString(16).length != 1
          ? parseInt(c).toString(16)
          : '0' + parseInt(c).toString(16);
    });
    
    //alpha value change
    if (rgba[3]) {
      hex += parseInt(`${255*rgba[3]}`).toString(16);
    }
    
    return `#${hex.toUpperCase()}`;
  }
  
  //hex validation check
  function validHEX(hex) {
  	if(typeof hex !=='string'){
      return false;
    }
	var reg = new RegExp(/^\#?[0-9a-fA-F]{6,8}$/);
    return reg.test(hex);
  }
  
  //HEX → RGBA
  function HEX2RGBA(hex){
  
	if(!validHEX(hex)){
    	throw new Error(`'${hex}' is not valid hex format!`);
    }
    
    let temp = hex.replace("#","");
    let len = temp.length/2;
    let rgba = [];
    for(let i=0; i<len; i++){
      let hTarget = temp.substring(i*2,(i+1)*2);
      //alpha value(0~1)
      if(i===3){
        rgba.push(parseInt(hTarget,16)/255);
      }
      else{//r,g,b value (0~255)
        rgba.push(parseInt(hTarget,16));
      }
    }
    return rgba;
  }
반응형