A comprehensive guide to color balance - the adjustment of color intensities to achieve neutral whites and accurate color reproduction across shadows, midtones, and highlights in digital images.
Color balance refers to the global adjustment of color intensities in an image to achieve accurate color reproduction and neutral whites. It's fundamental to photography, video production, and digital imaging, ensuring that colors appear natural under different lighting conditions.
Professional photo editing and enhancement tools powered by AI for photographers and content creators.
Remove backgrounds instantly • Resize without quality loss • Extract color palettes • Professional results
Color balance primarily involves two adjustments:
// Color balance adjustment system
class ColorBalanceProcessor {
constructor() {
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
}
// Apply color balance adjustment
adjustColorBalance(imageData, shadows = {}, midtones = {}, highlights = {}) {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
// Default balance adjustments (cyan-red, magenta-green, yellow-blue)
const defaultBalance = { cyan: 0, magenta: 0, yellow: 0 };
const shadowBalance = { ...defaultBalance, ...shadows };
const midtoneBalance = { ...defaultBalance, ...midtones };
const highlightBalance = { ...defaultBalance, ...highlights };
for (let i = 0; i < data.length; i += 4) {
const r = data[i] / 255;
const g = data[i + 1] / 255;
const b = data[i + 2] / 255;
// Calculate luminance to determine tone range
const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
// Calculate tone weights
const shadowWeight = this.calculateToneWeight(luminance, 'shadow');
const midtoneWeight = this.calculateToneWeight(luminance, 'midtone');
const highlightWeight = this.calculateToneWeight(luminance, 'highlight');
// Apply color balance adjustments
const adjustments = this.blendColorAdjustments(
shadowBalance, shadowWeight,
midtoneBalance, midtoneWeight,
highlightBalance, highlightWeight
);
// Convert adjustments to RGB modifications
const { rMod, gMod, bMod } = this.convertBalanceToRGB(adjustments);
// Apply modifications
result[i] = Math.max(0, Math.min(255, (r + rMod) * 255));
result[i + 1] = Math.max(0, Math.min(255, (g + gMod) * 255));
result[i + 2] = Math.max(0, Math.min(255, (b + bMod) * 255));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
calculateToneWeight(luminance, toneRange) {
switch (toneRange) {
case 'shadow':
return luminance < 0.33 ? 1 - (luminance / 0.33) : 0;
case 'midtone':
if (luminance >= 0.33 && luminance <= 0.66) {
const center = 0.495;
const distance = Math.abs(luminance - center);
return 1 - (distance / 0.165);
}
return 0;
case 'highlight':
return luminance > 0.66 ? (luminance - 0.66) / 0.34 : 0;
default:
return 0;
}
}
blendColorAdjustments(shadowAdj, shadowWeight, midtoneAdj, midtoneWeight, highlightAdj, highlightWeight) {
return {
cyan: (shadowAdj.cyan * shadowWeight + midtoneAdj.cyan * midtoneWeight + highlightAdj.cyan * highlightWeight),
magenta: (shadowAdj.magenta * shadowWeight + midtoneAdj.magenta * midtoneWeight + highlightAdj.magenta * highlightWeight),
yellow: (shadowAdj.yellow * shadowWeight + midtoneAdj.yellow * midtoneWeight + highlightAdj.yellow * highlightWeight)
};
}
convertBalanceToRGB(adjustments) {
const { cyan, magenta, yellow } = adjustments;
const factor = 0.01; // Adjustment intensity
return {
rMod: (-cyan + magenta) * factor,
gMod: (-cyan - magenta + yellow) * factor,
bMod: (cyan - yellow) * factor
};
}
// Temperature-based color balance
adjustTemperature(imageData, temperature = 6500, tint = 0) {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
// Calculate color temperature multipliers
const tempMultipliers = this.calculateTemperatureMultipliers(temperature);
const tintFactor = 1 + (tint / 100);
for (let i = 0; i < data.length; i += 4) {
const r = data[i] / 255;
const g = data[i + 1] / 255;
const b = data[i + 2] / 255;
// Apply temperature correction
const correctedR = r * tempMultipliers.r;
const correctedG = g * tempMultipliers.g * tintFactor;
const correctedB = b * tempMultipliers.b;
result[i] = Math.max(0, Math.min(255, correctedR * 255));
result[i + 1] = Math.max(0, Math.min(255, correctedG * 255));
result[i + 2] = Math.max(0, Math.min(255, correctedB * 255));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
calculateTemperatureMultipliers(temperature) {
// Simplified Planckian locus approximation
const temp = Math.max(1000, Math.min(40000, temperature));
const tempK = temp / 100;
let r, g, b;
// Red component
if (tempK <= 66) {
r = 255;
} else {
r = tempK - 60;
r = 329.698727446 * Math.pow(r, -0.1332047592);
r = Math.max(0, Math.min(255, r));
}
// Green component
if (tempK <= 66) {
g = tempK;
g = 99.4708025861 * Math.log(g) - 161.1195681661;
g = Math.max(0, Math.min(255, g));
} else {
g = tempK - 60;
g = 288.1221695283 * Math.pow(g, -0.0755148492);
g = Math.max(0, Math.min(255, g));
}
// Blue component
if (tempK >= 66) {
b = 255;
} else if (tempK >= 19) {
b = tempK - 10;
b = 138.5177312231 * Math.log(b) - 305.0447927307;
b = Math.max(0, Math.min(255, b));
} else {
b = 0;
}
return {
r: r / 255,
g: g / 255,
b: b / 255
};
}
}// Automatic white balance using Gray World assumption
class GrayWorldBalancer {
constructor() {
this.processor = new ColorBalanceProcessor();
}
// Gray World white balance
grayWorldBalance(imageData, preserveLuminance = true) {
const { data, width, height } = imageData;
const pixelCount = width * height;
// Calculate average RGB values
let rSum = 0, gSum = 0, bSum = 0;
for (let i = 0; i < data.length; i += 4) {
rSum += data[i];
gSum += data[i + 1];
bSum += data[i + 2];
}
const rAvg = rSum / pixelCount;
const gAvg = gSum / pixelCount;
const bAvg = bSum / pixelCount;
// Calculate gray point
const grayPoint = preserveLuminance ?
(0.299 * rAvg + 0.587 * gAvg + 0.114 * bAvg) :
(rAvg + gAvg + bAvg) / 3;
// Calculate correction factors
const rFactor = grayPoint / rAvg;
const gFactor = grayPoint / gAvg;
const bFactor = grayPoint / bAvg;
// Apply correction
const result = new Uint8ClampedArray(data.length);
for (let i = 0; i < data.length; i += 4) {
result[i] = Math.max(0, Math.min(255, data[i] * rFactor));
result[i + 1] = Math.max(0, Math.min(255, data[i + 1] * gFactor));
result[i + 2] = Math.max(0, Math.min(255, data[i + 2] * bFactor));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
// White patch algorithm
whitePatchBalance(imageData, percentile = 99) {
const { data, width, height } = imageData;
// Collect all pixel values
const rValues = [];
const gValues = [];
const bValues = [];
for (let i = 0; i < data.length; i += 4) {
rValues.push(data[i]);
gValues.push(data[i + 1]);
bValues.push(data[i + 2]);
}
// Sort values
rValues.sort((a, b) => b - a);
gValues.sort((a, b) => b - a);
bValues.sort((a, b) => b - a);
// Find percentile values (brightest pixels)
const index = Math.floor((100 - percentile) / 100 * rValues.length);
const rWhite = rValues[index];
const gWhite = gValues[index];
const bWhite = bValues[index];
// Calculate correction factors
const maxWhite = Math.max(rWhite, gWhite, bWhite);
const rFactor = maxWhite / rWhite;
const gFactor = maxWhite / gWhite;
const bFactor = maxWhite / bWhite;
// Apply correction
const result = new Uint8ClampedArray(data.length);
for (let i = 0; i < data.length; i += 4) {
result[i] = Math.max(0, Math.min(255, data[i] * rFactor));
result[i + 1] = Math.max(0, Math.min(255, data[i + 1] * gFactor));
result[i + 2] = Math.max(0, Math.min(255, data[i + 2] * bFactor));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
// Automatic color balance with multiple algorithms
autoBalance(imageData, method = 'grayWorld') {
switch (method) {
case 'grayWorld':
return this.grayWorldBalance(imageData);
case 'whitePatch':
return this.whitePatchBalance(imageData);
case 'hybrid':
return this.hybridBalance(imageData);
default:
return this.grayWorldBalance(imageData);
}
}
hybridBalance(imageData) {
// Combine gray world and white patch methods
const grayResult = this.grayWorldBalance(imageData);
const whiteResult = this.whitePatchBalance(imageData);
// Blend results (50/50)
const { data: grayData } = grayResult;
const { data: whiteData } = whiteResult;
const { width, height } = imageData;
const result = new Uint8ClampedArray(grayData.length);
for (let i = 0; i < grayData.length; i += 4) {
result[i] = Math.round((grayData[i] + whiteData[i]) / 2);
result[i + 1] = Math.round((grayData[i + 1] + whiteData[i + 1]) / 2);
result[i + 2] = Math.round((grayData[i + 2] + whiteData[i + 2]) / 2);
result[i + 3] = grayData[i + 3];
}
return new ImageData(result, width, height);
}
}// Color balance in LAB color space
class LABColorBalancer {
constructor() {
this.processor = new ColorBalanceProcessor();
}
// Adjust color balance in LAB space
adjustLABBalance(imageData, aShift = 0, bShift = 0) {
const { data, width, height } = imageData;
const result = new Uint8ClampedArray(data.length);
for (let i = 0; i < data.length; i += 4) {
const r = data[i] / 255;
const g = data[i + 1] / 255;
const b = data[i + 2] / 255;
// Convert RGB to LAB
const lab = this.rgbToLab(r, g, b);
// Adjust A and B channels
lab.a += aShift;
lab.b += bShift;
// Convert back to RGB
const rgb = this.labToRgb(lab.l, lab.a, lab.b);
result[i] = Math.max(0, Math.min(255, rgb.r * 255));
result[i + 1] = Math.max(0, Math.min(255, rgb.g * 255));
result[i + 2] = Math.max(0, Math.min(255, rgb.b * 255));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
rgbToLab(r, g, b) {
// Convert RGB to XYZ
let x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375;
let y = r * 0.2126729 + g * 0.7151522 + b * 0.0721750;
let z = r * 0.0193339 + g * 0.1191920 + b * 0.9503041;
// Normalize for D65 illuminant
x /= 0.95047;
y /= 1.00000;
z /= 1.08883;
// Apply gamma correction
x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x + 16/116);
y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y + 16/116);
z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z + 16/116);
return {
l: 116 * y - 16,
a: 500 * (x - y),
b: 200 * (y - z)
};
}
labToRgb(l, a, b) {
// Convert LAB to XYZ
let y = (l + 16) / 116;
let x = a / 500 + y;
let z = y - b / 200;
// Apply inverse gamma correction
x = Math.pow(x, 3) > 0.008856 ? Math.pow(x, 3) : (x - 16/116) / 7.787;
y = Math.pow(y, 3) > 0.008856 ? Math.pow(y, 3) : (y - 16/116) / 7.787;
z = Math.pow(z, 3) > 0.008856 ? Math.pow(z, 3) : (z - 16/116) / 7.787;
// Denormalize for D65 illuminant
x *= 0.95047;
y *= 1.00000;
z *= 1.08883;
// Convert XYZ to RGB
const r = x * 3.2404542 + y * -1.5371385 + z * -0.4985314;
const g = x * -0.9692660 + y * 1.8760108 + z * 0.0415560;
const bValue = x * 0.0556434 + y * -0.2040259 + z * 1.0572252;
return {
r: Math.max(0, Math.min(1, r)),
g: Math.max(0, Math.min(1, g)),
b: Math.max(0, Math.min(1, bValue))
};
}
// Neutralize color cast
neutralizeColorCast(imageData, targetNeutral = { r: 128, g: 128, b: 128 }) {
const { data, width, height } = imageData;
// Find the actual neutral point in the image
const actualNeutral = this.findNeutralPoint(data);
// Calculate correction needed
const rCorrection = targetNeutral.r / actualNeutral.r;
const gCorrection = targetNeutral.g / actualNeutral.g;
const bCorrection = targetNeutral.b / actualNeutral.b;
const result = new Uint8ClampedArray(data.length);
for (let i = 0; i < data.length; i += 4) {
result[i] = Math.max(0, Math.min(255, data[i] * rCorrection));
result[i + 1] = Math.max(0, Math.min(255, data[i + 1] * gCorrection));
result[i + 2] = Math.max(0, Math.min(255, data[i + 2] * bCorrection));
result[i + 3] = data[i + 3];
}
return new ImageData(result, width, height);
}
findNeutralPoint(data) {
// Find pixels that are likely neutral (low saturation)
const neutralPixels = [];
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
// Calculate saturation
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const saturation = max > 0 ? (max - min) / max : 0;
// Include pixels with low saturation
if (saturation < 0.1 && max > 50 && max < 200) {
neutralPixels.push({ r, g, b });
}
}
if (neutralPixels.length === 0) {
return { r: 128, g: 128, b: 128 };
}
// Calculate average of neutral pixels
const sum = neutralPixels.reduce(
(acc, pixel) => ({
r: acc.r + pixel.r,
g: acc.g + pixel.g,
b: acc.b + pixel.b
}),
{ r: 0, g: 0, b: 0 }
);
return {
r: sum.r / neutralPixels.length,
g: sum.g / neutralPixels.length,
b: sum.b / neutralPixels.length
};
}
}// Complete color balance workflow for photography
class PhotographyColorBalance {
constructor() {
this.processor = new ColorBalanceProcessor();
this.grayWorld = new GrayWorldBalancer();
this.labBalancer = new LABColorBalancer();
}
// Process RAW-like color balance workflow
processImage(imageData, settings = {}) {
const {
autoWhiteBalance = false,
temperature = 6500,
tint = 0,
shadowBalance = { cyan: 0, magenta: 0, yellow: 0 },
midtoneBalance = { cyan: 0, magenta: 0, yellow: 0 },
highlightBalance = { cyan: 0, magenta: 0, yellow: 0 },
preserveLuminance = true
} = settings;
let result = imageData;
// Step 1: Auto white balance if requested
if (autoWhiteBalance) {
result = this.grayWorld.autoBalance(result, 'hybrid');
}
// Step 2: Apply temperature and tint
if (temperature !== 6500 || tint !== 0) {
result = this.processor.adjustTemperature(result, temperature, tint);
}
// Step 3: Apply color balance adjustments
const hasColorBalance =
this.hasAdjustments(shadowBalance) ||
this.hasAdjustments(midtoneBalance) ||
this.hasAdjustments(highlightBalance);
if (hasColorBalance) {
result = this.processor.adjustColorBalance(
result,
shadowBalance,
midtoneBalance,
highlightBalance
);
}
return result;
}
hasAdjustments(balance) {
return balance.cyan !== 0 || balance.magenta !== 0 || balance.yellow !== 0;
}
// Analyze image for color balance issues
analyzeColorBalance(imageData) {
const { data, width, height } = imageData;
const pixelCount = width * height;
// Calculate average RGB values
let rSum = 0, gSum = 0, bSum = 0;
let shadowRSum = 0, shadowGSum = 0, shadowBSum = 0;
let highlightRSum = 0, highlightGSum = 0, highlightBSum = 0;
let shadowCount = 0, highlightCount = 0;
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
rSum += r;
gSum += g;
bSum += b;
if (luminance < 85) { // Shadows
shadowRSum += r;
shadowGSum += g;
shadowBSum += b;
shadowCount++;
} else if (luminance > 170) { // Highlights
highlightRSum += r;
highlightGSum += g;
highlightBSum += b;
highlightCount++;
}
}
const analysis = {
overall: {
rAvg: rSum / pixelCount,
gAvg: gSum / pixelCount,
bAvg: bSum / pixelCount
},
shadows: shadowCount > 0 ? {
rAvg: shadowRSum / shadowCount,
gAvg: shadowGSum / shadowCount,
bAvg: shadowBSum / shadowCount
} : null,
highlights: highlightCount > 0 ? {
rAvg: highlightRSum / highlightCount,
gAvg: highlightGSum / highlightCount,
bAvg: highlightBSum / highlightCount
} : null
};
// Calculate color cast indicators
const overallGray = (analysis.overall.rAvg + analysis.overall.gAvg + analysis.overall.bAvg) / 3;
analysis.colorCast = {
red: analysis.overall.rAvg - overallGray,
green: analysis.overall.gAvg - overallGray,
blue: analysis.overall.bAvg - overallGray
};
// Suggest corrections
analysis.suggestions = this.generateSuggestions(analysis);
return analysis;
}
generateSuggestions(analysis) {
const suggestions = [];
const { colorCast } = analysis;
const threshold = 5;
if (Math.abs(colorCast.red) > threshold) {
suggestions.push({
type: 'temperature',
adjustment: colorCast.red > 0 ? 'cooler' : 'warmer',
strength: Math.abs(colorCast.red)
});
}
if (Math.abs(colorCast.green) > threshold) {
suggestions.push({
type: 'tint',
adjustment: colorCast.green > 0 ? 'magenta' : 'green',
strength: Math.abs(colorCast.green)
});
}
return suggestions;
}
}Explore these comprehensive pillar articles related to Color Balance
A comprehensive guide to tetradic color schemes - sophisticated four-color harmonies that use two complementary pairs arranged in rectangular or square formations on the color wheel, providing maximum color variety while maintaining structured relationships essential for dynamic design compositions, brand systems, and advanced color theory applications.
A comprehensive guide to split-complementary color schemes - sophisticated three-color harmonies that combine a base color with two colors adjacent to its complement, creating balanced visual contrast with reduced tension compared to direct complementary pairs, essential for refined design compositions, brand identity systems, and advanced color theory applications.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Discover more about Color Balance and related color theory concepts
A comprehensive guide to split-complementary color schemes - sophisticated three-color harmonies that combine a base color with two colors adjacent to its complement, creating balanced visual contrast with reduced tension compared to direct complementary pairs, essential for refined design compositions, brand identity systems, and advanced color theory applications.
A comprehensive guide to tetradic color schemes - sophisticated four-color harmonies that use two complementary pairs arranged in rectangular or square formations on the color wheel, providing maximum color variety while maintaining structured relationships essential for dynamic design compositions, brand systems, and advanced color theory applications.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
A comprehensive guide to monochromatic color schemes - sophisticated single-hue harmonies that create unified visual experiences through systematic variations in saturation, lightness, and tonal relationships, essential for elegant design compositions, brand consistency, and advanced color theory applications requiring cohesive aesthetic unity.
Comprehensive guide to triadic color schemes - three colors evenly spaced around the color wheel that create balanced, vibrant, and dynamic visual compositions with mathematical precision and artistic appeal.
Disclosure: The links below are Amazon affiliate links. RGBmatic earns a commission from qualifying purchases at no extra cost to you.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary