developer tip

16 진수 색상이 "너무 검은 색"인지 확인하는 방법은 무엇입니까?

optionbox 2020. 8. 20. 08:11
반응형

16 진수 색상이 "너무 검은 색"인지 확인하는 방법은 무엇입니까?


색상 선택기에서 선택한 색상의 어둡기를 평가하여 "너무 검은 색"인지 확인하고, 그렇다면 흰색으로 설정합니다. 나는 이것을 풀기 위해 16 진수 값의 첫 번째 문자를 사용할 수 있다고 생각했습니다. 작동하지만 합법적으로 "밝은"색상도 전환하고 있습니다.

이 작업을 코드가 있습니다.

        if (lightcolor.substring(0,3) == "#00"|| lightcolor.substring(0,3) == "#010"){
            lightcolor="#FFFFFF";
            color=lightcolor;
        }

색상이 특정 수준의 어둠을 넘어 섰다는 것을 알기 위해 16 진수 수학으로 더 효율적인 방법이 있어야합니까? lightcolor + "some hex value"<= "some hex value"와 같이 흰색으로 설정합니다.

나는 이것을 위해 사용될 수있는 tinyColor가 추가되었지만 확실하지 않습니다.

무리!


세 가지 RGB 구성 요소를 개별적으로 추출한 다음 표준 공식을 사용하여 결과 RGB 값을인지 된 밝기로 변환해야합니다.

6 자 색상 가정 :

var c = c.substring(1);      // strip #
var rgb = parseInt(c, 16);   // convert rrggbb to decimal
var r = (rgb >> 16) & 0xff;  // extract red
var g = (rgb >>  8) & 0xff;  // extract green
var b = (rgb >>  0) & 0xff;  // extract blue

var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709

if (luma < 40) {
    // pick a different colour
}

편집하다

5 월 2014 년부터 tinycolor지금이 getBrightness()대신 위의 ITU-R 것들의 요소에 가중치를 CCIR601를 사용하여 불구하고 기능을,.

편집하다

결과 루마 값 범위는 0..255입니다. 여기서 0은 가장 어둡고 255는 가장 밝습니다. 128보다 큰 값은에서 밝은 것으로 간주됩니다 tinycolor. (@ pau.moreno 및 @Alnitak의 댓글에서 뻔뻔스럽게 복사 됨)


TinyColor의 라이브러리는 (당신이 이미 언급 한) 검사와 그들 사이에 색상을 조작하기위한 여러 가지 기능을 제공합니다 :

  • getBrightness

    Web Content Accessibility Guidelines (버전 1.0)에 정의 된대로 0-255 범위에서 색상의인지 된 밝기를 반환합니다 .

    tinycolor("#fff").getBrightness(); // 255
    
  • isLight

    색상의 감지 된 밝기가 밝은 지 여부를 나타내는 부울을 반환합니다.

    tinycolor("#fff").isLight(); // true
    tinycolor("#000").isLight(); // false
    
  • isDark

    색상의 감지 된 밝기가 어두운 지 여부를 나타내는 부울을 반환합니다.

    tinycolor("#fff").isDark(); // false
    tinycolor("#000").isDark(); // true
    
  • getLuminance

    Web Content Accessibility Guidelines (버전 2.0)에 정의 된대로 0-1에서 색상의인지 된 광도를 반환합니다 .

    tinycolor("#fff").getLuminance(); // 1
    

WooCommerce Wordpress PHP 함수 ( wc_hex_is_light )를 발견 하고 JavaScript로 변환했습니다. 잘 작동합니다!

function wc_hex_is_light(color) {
    const hex = color.replace('#', '');
    const c_r = parseInt(hex.substr(0, 2), 16);
    const c_g = parseInt(hex.substr(2, 2), 16);
    const c_b = parseInt(hex.substr(4, 2), 16);
    const brightness = ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000;
    return brightness > 155;
}

휘도 를 계산할 수 있습니다 .

따라서 휘도는 표면이 얼마나 밝게 나타나는지를 나타내는 지표입니다.

따라서 텍스트가 흰색인지 검은 색인지 선택하는 것이 좋습니다.

var getRGB = function(b){
    var a;
    if(b&&b.constructor==Array&&b.length==3)return b;
    if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b))return[parseInt(a[1]),parseInt(a[2]),parseInt(a[3])];
    if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];
    if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b))return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],
16)];
    if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];
    return (typeof (colors) != "undefined")?colors[jQuery.trim(b).toLowerCase()]:null
};

var luminance_get = function(color) {
    var rgb = getRGB(color);
    if (!rgb) return null;
        return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
}

위의 방법을 사용하면 색상을 다른 형식으로 전달할 수 있지만 알고리즘은 기본적으로 luminance_get.

내가 그것을 사용할 때, 휘도가 더 크면 색상을 검정색으로 설정하고 180그렇지 않으면 흰색으로 설정했습니다.


There's an important distinction here between luminance and brightness. Luminance, at the end of the day, is a measure of how much energy travels through a certain area and completely ignores how our perceptual systems perceive that energy. Brightness, on the other hand, is a measure of how we perceive that energy and takes into the account the relationship between luminance and our perceptual system. (As a point of confusion, there is a term called relative luminance, which seems to be used synonymously with brightness terms. It tripped me up good).

To be precise, you are looking for "brightness" or "value" or "relatively luminance" as others have suggested. You can calculate this in several different way (such is to be human!) http://en.wikipedia.org/wiki/HSL_and_HSV#Lightness

  1. Take the max of R, G, and B.
  2. Take the average of the max and the min from R, G, and B.
  3. Take the average of all three.
  4. Use some weighted average as others have suggested here.

This work with hex e.g #fefefe

function isTooDark(hexcolor){
    var r = parseInt(hexcolor.substr(1,2),16);
    var g = parseInt(hexcolor.substr(3,2),16);
    var b = parseInt(hexcolor.substr(4,2),16);
    var yiq = ((r*299)+(g*587)+(b*114))/1000;
    // Return new color if to dark, else return the original
    return (yiq < 40) ? '#2980b9' : hexcolor;
}

You can change it to return true or false by change

return (yiq < 40) ? '#2980b9' : hexcolor;

to

return (yiq < 40);

A possible solution would be to convert your color from RGB to HSB. HSB stands for hue, saturation, and brightness (also known as HSV, where V is for value). Then you have just one parameter to check: brightness.


I realize this conversation is a few years old, but it is still relevant. I wanted to add that my team was having the same issue in Java (SWT) and found this to be a bit more accurate:

private Color getFontColor(RGB bgColor) {
    Color COLOR_BLACK = new Color(Display.getDefault(), 0, 0, 0);
    Color COLOR_WHITE = new Color(Display.getDefault(), 255, 255, 255);

    double luminance = Math.sqrt(0.241 
       * Math.pow(bgColor.red, 2) + 0.691 * Math.pow(bgColor.green, 2) +  0.068 
       * Math.pow(bgColor.blue, 2));
    if (luminance >= 130) {
        return COLOR_BLACK;
    } else {
        return COLOR_WHITE;
    }
}

참고URL : https://stackoverflow.com/questions/12043187/how-to-check-if-hex-color-is-too-black

반응형