Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to convert semi-transparent to solid color

Let's say I have the color rgba(255, 0, 0, 0.5) on a white background. The color that can bee seen is almost identical to rgba(255, 140, 140, 1) which is a solid color. I'm looking for an algorithm that converts a semi-transparent color (over white) to a solid color so that it looks (pretty much) the same when it's one near each other (like in the photo below)

Two rectangles with diferent colors that look the same on a white background

I noticed that if there are 2 components (r, g, or b) that are 0, then you have to keep the not-null component's value and adjust the null components by the same value so that it matches the wight color. This value (I guess) depends on the alpha component of semi-transparent color. But I can't seem to find the formula. How about the rest of the case? I think there must be a general formula that can be applied.

I'm looking for an answer in pseudocode, javascript, Java, Python, C# or C++.

Also, I am not working on any project. This question is for learning purposes and for helping people that might need this.

like image 639
Stefan Octavian Avatar asked Jul 17 '26 15:07

Stefan Octavian


1 Answers

I know this formula to convert from rgba to rgb

function rgba2rgb(background, color) {
    const alpha = color[3]

  return [Math.floor((1 - alpha) * background[0] + alpha * color[0] + 0.5),
        Math.floor((1 - alpha) * background[1] + alpha * color[1] + 0.5),
        Math.floor((1 - alpha) * background[2] + alpha * color[2] + 0.5)]
}

console.log(rgba2rgb([255, 255, 255], [255, 0, 0, 0.5])) // [ 255, 128, 128 ]

But it's not right for your example


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!