Convert 8-digit hex colors to rgba colors?

前端 未结 2 1560
我寻月下人不归
我寻月下人不归 2020-11-29 05:55

Everything I\'ve found on this subject simply converts the hex to rgb and then adds an alpha of 1. I want to get the intended alpha from the hex digits as well.

A c

相关标签:
2条回答
  • 2020-11-29 06:32

    Here is a little tooltip for you :

    In this case #DCDCDC8F the DC is alpha = 220,

    Hex to Decimal [ DC ]:

    1. first place D = 13 * 16^1 = 208
    2. second place C = 12 * 16^0 = 12
    3. sum = 12 + 208 = 220

    then 220 / 255 = 0.86 opacity.

    enter image description here

    The bytes are stored in memory on a little-endian machine in the order AABBGGRR

    Check this : http://www.statman.info/conversions/hexadecimal.html

    0 讨论(0)
  • 2020-11-29 06:47

    I have made a quick JSfiddle form that allows you to convert from 8-digit hex code into CSS rgba values ;)

    https://jsfiddle.net/teddyrised/g02s07n4/embedded/result/

    The basis is rather simple — to split the string you have provided into parts of 2-digits, and perform conversion into percentage ratios for the alpha channel, and to decimals for the RGB channels. The markup is as follow:

    <form action="">
        <select id="format">
            <option value="rgba">RGBa: RRGGBBAA</option>
            <option value="argb">aRGB: AARRGGBB</option>
        </select>
        <input type="text" id="hex" value="#949494E8" />
        <button>Convert</button>
    </form>
    <p id="rgba"></p>
    

    The logic:

    // Remove hash
    var hex = $('#hex').val().slice(1);
    
    // Split to four channels
    var c = hex.match(/.{1,2}/g);
    
    // Function: to decimals (for RGB)
    var d = function(v) {
        return parseInt(v, 16);
    };
    // Function: to percentage (for alpha), to 3 decimals
    var p = function(v) {
        return parseFloat(parseInt((parseInt(v, 16)/255)*1000)/1000);
    };
    
    // Check format: if it's argb, pop the alpha value from the end and move it to front
    var a, rgb=[];
    if($('#format').val() === 'argb') {
        c.push(c.shift());
    }
    
    // Convert array into rgba values
    a = p(c[3]);
    $.each(c.slice(0,3), function(i,v) {
        rgb.push(d(v));
    });
    

    The gist of conversion is as follow:

    • Converting the RGB channels in hex, into decimal values. This is done by using parseInt(hexValue, 16).
    • Converting the alpha channel in hex, into percentage ratio. This is done by simply converting it to decimal values (see above point), and calculating its relative value to 255.
    0 讨论(0)
提交回复
热议问题