With modern web APIs, we can process and edit complex photos within milliseconds without server dependencies. Background removing and replacement rely on color filters called Chroma Keying.

1. RGB Euclidean Distance

To replace a specific background color, we must identify which pixels are "background" and which belong to the "foreground." The algorithm loops through the image matrix and gauges distance: $$D = \sqrt{(R_1 - R_2)^2 + (G_1 - G_2)^2 + (B_1 - B_2)^2}$$ If the distance $D$ is less than a user-configured Tolerance, we classify the pixel as background and set its transparency (Alpha channel) to 0.

2. Eliminating Jagged Edges: Edge Feathering

A hard binary threshold (on/off) creates pixelated, jagged, and unnatural borders. To fix this, feathering zones are introduced:

  • Within Tolerance: Absolute transparency (Alpha = 0).
  • Smooth Gradient Region: Linear scaling from transparent to fully opaque. This blends foreground hair and smooth curves neatly with your fallback background.

3. Replacing with Custom ID Background Colors

For standard ID photos, once the alpha values are computed, we can composite the remaining foreground pixels onto solid colors (e.g., standard red: #d93c3c, blue: #438EDB, or white). The composition blends colors seamlessly using alpha blending equations.