Converting ARBG to RGB with alpha blending with a

2019-04-13 06:57发布

问题:

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?

回答1:

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)


回答2:

None of the proposed worked for me, but then used http://en.wikipedia.org/wiki/Alpha_compositing to come up with this:

var useColor = Color.FromArgb(
                (int)((theStructureColor.R) * (theStructureColor.A / 255.0) + 255 - theStructureColor.A),
                (int)((theStructureColor.G) * (theStructureColor.A / 255.0) + 255 - theStructureColor.A),
                (int)((theStructureColor.B) * (theStructureColor.A / 255.0) + 255 - theStructureColor.A));


回答3:

So what you are really doing is combining a white background with a semi-transparent foreground color, and calculating the resulting display color. This seems to be a duplicate question of Calculate resulting RGB from 2 colors, one is transparent, where a suitable answer was posted. To apply it to your situation, it would be something like the following (note, I haven't tested this code):

public static Color FromTransparentWithWhiteBG(Color A)
{
    // Assuming Alpha is a value between 0 and 254...
    var aFactor = (A.A/254);
    var bgAFactor = (1-(A.A/254));
    var background = Color.White;
    var R_c = (Int32)(Math.Ceiling((Double)A.R * aFactor) + Math.Ceiling ((Double)background.R * (1 - bgAFactor )));
    var G_c = (Int32)(Math.Ceiling((Double)A.G * aFactor) + Math.Ceiling ((Double)background.G * (1 - bgAFactor )));
    var B_c = (Int32)(Math.Ceiling((Double)A.B * aFactor) + Math.Ceiling ((Double)background.B * (1 - bgAFactor )));
    return Color.FromArgb(1, R_c, G_c, B_c);
}