Search code examples
c#rgbalphablendingargb

Converting ARBG to RGB with alpha blending with a White Background


I have a color hex string stored in the database like 0x78dce6b0; I can convert this to an ARGB color using:

string colorString=0x78dce6b0;
int hexColor = Convert.ToInt32(colorString ?? "0", 16);
Color colorTL = Color.FromArgb(hexColor);

Now I want to convert this to use in an HTML page, so I need to convert into an HTML value like #cc3388. If I directly convert using ColorTranslator.ToHtml(colorTL), I lose the alpha blending value. How do I convert it by taking into consideration the alpha value, assuming the background is always white?


Solution

  • HTML Colors do not have an Alpha component.

    Unfortunately it is impossible to convert ARGB to HTML RGB without losing the Alpha component.

    If you want to blend your color with white, based upon your alpha value...

    • Convert each Hex component (A, R, G, B) into a value from 0 to 255, where a value of FF equates to 255, 00 equates to 0.
    • We'll name these 0-255 values, A, R, G, B
    • We'll assume that an Alpha value of 255 means "fully transparent" and an Alpha value of 0 means "fully opaque"
    • New_R = CInt((255 - R) * (A / 255.0) + R)
    • New_G = CInt((255 - G) * (A / 255.0) + G)
    • New_B = CInt((255 - G) * (A / 255.0) + B)
    • Your final HTML color string will be: "#" & cstr(New_R) & cstr(New_G) & cstr(New_B)