Mark Lalor
Mark Lalor

Reputation: 7887

Get pixel color after alpha blend

I have a RGBA color like

255, 0, 0, 100

How can I get the RGB if it was put onto a white background? eg. this red would become lighter and be more like

255, 100, 100

And the same thing if it were put onto a black background.

Does this make enough sense?

Preferably c++

Upvotes: 0

Views: 3428

Answers (2)

Mike Bailey
Mike Bailey

Reputation: 12817

As an example to my comment:

struct Color
{
    int R;
    int G;
    int B;
    int A;
};

Color Blend(Color c1, Color c2)
{
    Color result;
    double a1 = c1.A / 255.0;
    double a2 = c2.A / 255.0;

    result.R = (int) (a1 * c1.R + a2 * (1 - a1) * c2.R);
    result.G = (int) (a1 * c1.G + a2 * (1 - a1) * c2.G);
    result.B = (int) (a1 * c1.B + a2 * (1 - a1) * c2.B);
    result.A = (int) (255 * (a1 + a2 * (1 - a1)));
    return result;
}


void Example()
{
    Color c1;
    c1.R = 255;
    c1.G = 0;
    c1.B = 0;
    c1.A = 100;

    Color c2;
    c2.R = 255;
    c2.G = 255;
    c2.B = 255;

    Color blended = Blend(c1, c2);
    int x = 50;
    int y = 100;

    // Pretend function that draws a pixel at (x, y) with rgb values
    DrawPixel(x, y, blended.R, blended.G, blended.B);
}

Upvotes: 3

Ben Voigt
Ben Voigt

Reputation: 283664

It depends on the blending function.

Nine different blending functions, with a formula for each, are described in the glBlendFunc documentation.

Upvotes: -1

Related Questions