Converting RGBA to RGB tailored

Possible duplicate:
Convert RGBA to RGB color

I am trying to convert a RGBA color from alpha-1 to a solid RGB representation considering the background color.

Using the algorithm provided in this question , I manage to get the correct conversion to a solid RGB color - BUT ONLY when alpha = 0.5.

Here is my test code:

<!DOCTYPE html> <html> <head></head> <body> <script type="text/javascript"> // Basic RGB(A) to CSS property value function _toString(obj) { var type = 'rgb', out = obj.red + ', ' + obj.green + ', ' + obj.blue; if (obj.alpha !== undefined) { type += 'a'; out += ', ' + obj.alpha; } return type + '(' + out + ')'; } // Background color, assume this is always RGB var bg = {red: 255, green: 51, blue: 0}; // RGBA color var RGBA = {red: 0, green: 102, blue: 204, alpha: 0}; // Output RGB var RGB = {red: null, green: null, blue: null}; // Just a cache... var alpha; while (RGBA.alpha < 1) { alpha = 1 - RGBA.alpha; RGB.red = Math.round((alpha * (RGBA.red / 255) + ((1 - RGBA.alpha) * (bg.red / 255))) * 255); RGB.green = Math.round((alpha * (RGBA.green / 255) + ((1 - RGBA.alpha) * (bg.green / 255))) * 255); RGB.blue = Math.round((alpha * (RGBA.blue / 255) + ((1 - RGBA.alpha) * (bg.blue / 255))) * 255); document.write('<div style="display: block; width: 150px; height: 100px; background-color: ' + _toString(bg) + '">\ <div style="color: #fff; width: 50px; height: 50px; background-color: ' + _toString(RGBA) + '"><small>RGBA<br>' + RGBA.alpha + '</small></div>\ <div style="color: #fff; width: 50px; height: 50px; background-color: ' + _toString(RGB) + '"><small>RGB<br>' + RGBA.alpha + '</small></div>\ </div>'); // Increment alpha RGBA.alpha += 0.25; } </script> </body> </html> 

Performing the above in Chrome and Firefox leads to successful RGBA-> RGB with alpha 0.5, any deviation from 0.5 leads to a mismatch, very subtle if the deviation is very small (i.e. you can notice a problem when alpha is 0, 55).

I rewrote logic several times, completely expanding logic into its most basic parts, but I was not able to succeed.

+6
source share
1 answer

It sounds like you are trying to use a generic method for mixing, but the incremental loop throws me away. Called from OpenGL FAQs:

β€œThe typical use described above [for mixing] changes the input color by its associated alpha value and changes the destination color by one minus the input alpha value. Then the sum of these two colors is written back to the framebuffer.”

So, instead of a while loop use:

 alpha = 1 - RGBA.alpha; RGB.red = Math.round((RGBA.alpha * (RGBA.red / 255) + (alpha * (bg.red / 255))) * 255); RGB.green = Math.round((RGBA.alpha * (RGBA.green / 255) + (alpha * (bg.green / 255))) * 255); RGB.blue = Math.round((RGBA.alpha * (RGBA.blue / 255) + (alpha * (bg.blue / 255))) * 255); 
+7
source

Source: https://habr.com/ru/post/921136/


All Articles