Change brightness of web rgb colors

Recently needed to use an existing web color (like, the #rrggbb color definitions) and produce a “lighter” version of it. I found some javascript code to do this, which changed the “luminance” of a given web color, at this url: http://www.sitepoint.com/javascript-generate-lighter-darker-color/

So this is a .Net translation of this code: 

        public static string ColorLuminance(string hex, float lum)
        {

            // validate hex string
            hex = new Regex(@"[^0-9a-f]", RegexOptions.None).Replace(hex, "");
            //if abc, make aabbcc
            if (hex.Length < 6)
            {
                var hchr = hex.ToCharArray();
                hex = new string(new char[] { hchr[0], hchr[0], hchr[1], hchr[1], hchr[2], hchr[2] });
            }

            // convert to decimal and change luminosity
            string rgb = "#";
            for (int i = 0; i < 3; i++)
            {
                int c = Int32.Parse(hex.Substring(i * 2, 2), NumberStyles.HexNumber);
                string sc = Convert.ToInt32(Math.Round(Math.Min(Math.Max(0, c + (c * lum)), 255))).ToString("X2");
                rgb += sc; // ("00" + sc).Substring(sc.Length);
            }
            return rgb;
        }

Leave a Reply

Your email address will not be published.