RGB to hex and hex to RGB

前端 未结 30 2826
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 07:21

    I'm working with XAML data that has a hex format of #AARRGGBB (Alpha, Red, Green, Blue). Using the answers above, here's my solution:

    function hexToRgba(hex) {
        var bigint, r, g, b, a;
        //Remove # character
        var re = /^#?/;
        var aRgb = hex.replace(re, '');
        bigint = parseInt(aRgb, 16);
    
        //If in #FFF format
        if (aRgb.length == 3) {
            r = (bigint >> 4) & 255;
            g = (bigint >> 2) & 255;
            b = bigint & 255;
            return "rgba(" + r + "," + g + "," + b + ",1)";
        }
    
        //If in #RRGGBB format
        if (aRgb.length >= 6) {
            r = (bigint >> 16) & 255;
            g = (bigint >> 8) & 255;
            b = bigint & 255;
            var rgb = r + "," + g + "," + b;
    
            //If in #AARRBBGG format
            if (aRgb.length == 8) {
                a = ((bigint >> 24) & 255) / 255;
                return "rgba(" + rgb + "," + a.toFixed(1) + ")";
            }
        }
        return "rgba(" + rgb + ",1)";
    }
    

    http://jsfiddle.net/kvLyscs3/

提交回复
热议问题