Merge two layers with alpha channels

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.

///

/// Merges two pixel one on other
///

/// Back pane
/// 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

// calculate appropriate color values
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;

return Color.FromArgb(alpha, r, g, b);
}

Treat this code as mnemonic because types conversion has been skipped in this example in order to keep it simple.

Добавить комментарий

Fill in your details below or click an icon to log in:

Логотип WordPress.com

You are commenting using your WordPress.com account. Log Out / Изменить )

Фотография Twitter

You are commenting using your Twitter account. Log Out / Изменить )

Фотография Facebook

You are commenting using your Facebook account. Log Out / Изменить )

Connecting to %s

Follow

Get every new post delivered to your Inbox.