Recently I’ve faced interesting task and would like to share solution with community. Task sounds quite simple: “merge two images with (a,r,g,b) components (i.e. 24-bit) into single image, preserving right transparency and color values (for example as Photoshop does)”. The solution came only after very strong research, because formulas are not as simple as expected to be. Source code example presented below. /// Back pane // calculate appropriate color values return Color.FromArgb(alpha, r, g, b);
///
///
/// Front pane
/// Mixed pixel data (color), taking their alpha-channels into consideration
public static Color MergePixels(this Color lb, Color lf)
{
int alpha = lf.A + lb.A * (255 - lf.A) / 255;
if (alpha == 0) return Color.FromArgb(0, Color.White); // both layers are completely transparent, return opaque pixel
int r = (lf.A * lf.R + (alpha - lf.A) * lb.R) / alpha;
int g = (lf.A * lf.G + (alpha - lf.A) * lb.G) / alpha;
int b = (lf.A * lf.B + (alpha - lf.A) * lb.B) / alpha;
}
Treat this code as mnemonic because types conversion has been skipped in this example in order to keep it simple.
9 Фев