A comprehensive guide to color encoding - the process of representing and storing color information in digital formats, including bit depth, color spaces, and compression methods for optimal color reproduction and file efficiency.
Color encoding is the process of representing and storing color information in digital formats. It encompasses how colors are quantized, stored, and transmitted in digital systems, affecting both color accuracy and file size. Understanding color encoding is crucial for maintaining color fidelity across different devices and applications.
Digital systems represent colors using numerical values that approximate the continuous spectrum of visible light. The encoding method determines how accurately colors can be represented and how efficiently they can be stored.
// Comprehensive color encoding and processing system
class ColorEncodingProcessor {
constructor() {
// Supported bit depths and their characteristics
this.bitDepths = {
1: { colors: 2, description: 'Monochrome (black and white)' },
4: { colors: 16, description: '16-color palette' },
8: { colors: 256, description: '256-color palette or grayscale' },
16: { colors: 65536, description: 'High color (RGB565 or RGB555)' },
24: { colors: 16777216, description: 'True color (RGB888)' },
32: { colors: 16777216, description: 'True color with alpha (RGBA8888)' },
48: { colors: 281474976710656, description: 'Deep color (RGB161616)' },
64: { colors: 281474976710656, description: 'Deep color with alpha' }
};
// Color encoding formats
this.encodingFormats = {
'rgb565': { bits: 16, r: 5, g: 6, b: 5, alpha: false },
'rgb555': { bits: 16, r: 5, g: 5, b: 5, alpha: false },
'rgb888': { bits: 24, r: 8, g: 8, b: 8, alpha: false },
'rgba8888': { bits: 32, r: 8, g: 8, b: 8, alpha: 8 },
'rgb101010': { bits: 30, r: 10, g: 10, b: 10, alpha: false },
'rgba1010102': { bits: 32, r: 10, g: 10, b: 10, alpha: 2 },
'rgb161616': { bits: 48, r: 16, g: 16, b: 16, alpha: false },
'rgba16161616': { bits: 64, r: 16, g: 16, b: 16, alpha: 16 }
};
}
// Encode color to specific format
encodeColor(color, format, options = {}) {
const {
dithering = false,
gammaCorrection = true,
colorSpace = 'srgb'
} = options;
const formatSpec = this.encodingFormats[format];
if (!formatSpec) {
throw new Error(`Unsupported encoding format: ${format}`);
}
let { r, g, b, a = 255 } = color;
// Apply gamma correction if needed
if (gammaCorrection && colorSpace === 'srgb') {
r = this.applySRGBGamma(r / 255) * 255;
g = this.applySRGBGamma(g / 255) * 255;
b = this.applySRGBGamma(b / 255) * 255;
}
// Quantize to target bit depth
const quantized = this.quantizeColor(
{ r, g, b, a },
formatSpec,
dithering
);
// Pack into encoded format
const packed = this.packColor(quantized, formatSpec);
return {
original: color,
quantized,
packed,
format,
bitDepth: formatSpec.bits,
quality: this.assessQuantizationQuality(color, quantized)
};
}
// Decode color from encoded format
decodeColor(encodedValue, format, options = {}) {
const {
gammaCorrection = true,
colorSpace = 'srgb'
} = options;
const formatSpec = this.encodingFormats[format];
if (!formatSpec) {
throw new Error(`Unsupported encoding format: ${format}`);
}
// Unpack encoded value
const unpacked = this.unpackColor(encodedValue, formatSpec);
// Convert to full precision
const fullPrecision = this.expandColor(unpacked, formatSpec);
// Apply inverse gamma correction if needed
if (gammaCorrection && colorSpace === 'srgb') {
fullPrecision.r = this.removeSRGBGamma(fullPrecision.r / 255) * 255;
fullPrecision.g = this.removeSRGBGamma(fullPrecision.g / 255) * 255;
fullPrecision.b = this.removeSRGBGamma(fullPrecision.b / 255) * 255;
}
return {
decoded: fullPrecision,
encoded: encodedValue,
format,
bitDepth: formatSpec.bits
};
}
quantizeColor(color, formatSpec, dithering = false) {
const { r: rBits, g: gBits, b: bBits, alpha: aBits } = formatSpec;
let { r, g, b, a = 255 } = color;
// Apply dithering if requested
if (dithering) {
const ditherNoise = this.generateDitherNoise();
r += ditherNoise.r;
g += ditherNoise.g;
b += ditherNoise.b;
}
// Quantize each channel
const quantized = {
r: this.quantizeChannel(r, rBits),
g: this.quantizeChannel(g, gBits),
b: this.quantizeChannel(b, bBits)
};
if (aBits) {
quantized.a = this.quantizeChannel(a, aBits);
}
return quantized;
}
quantizeChannel(value, bits) {
const maxValue = (1 << bits) - 1;
const quantized = Math.round((value / 255) * maxValue);
return Math.max(0, Math.min(maxValue, quantized));
}
generateDitherNoise() {
// Simple random dithering
const strength = 0.5;
return {
r: (Math.random() - 0.5) * strength,
g: (Math.random() - 0.5) * strength,
b: (Math.random() - 0.5) * strength
};
}
packColor(quantized, formatSpec) {
const { r: rBits, g: gBits, b: bBits, alpha: aBits } = formatSpec;
let packed = 0;
let shift = 0;
// Pack in order: alpha, blue, green, red (little-endian style)
if (aBits) {
packed |= (quantized.a << shift);
shift += aBits;
}
packed |= (quantized.b << shift);
shift += bBits;
packed |= (quantized.g << shift);
shift += gBits;
packed |= (quantized.r << shift);
return packed;
}
unpackColor(packedValue, formatSpec) {
const { r: rBits, g: gBits, b: bBits, alpha: aBits } = formatSpec;
let shift = 0;
const unpacked = {};
// Unpack in reverse order
if (aBits) {
const aMask = (1 << aBits) - 1;
unpacked.a = (packedValue >> shift) & aMask;
shift += aBits;
}
const bMask = (1 << bBits) - 1;
unpacked.b = (packedValue >> shift) & bMask;
shift += bBits;
const gMask = (1 << gBits) - 1;
unpacked.g = (packedValue >> shift) & gMask;
shift += gBits;
const rMask = (1 << rBits) - 1;
unpacked.r = (packedValue >> shift) & rMask;
return unpacked;
}
expandColor(quantized, formatSpec) {
const { r: rBits, g: gBits, b: bBits, alpha: aBits } = formatSpec;
const expanded = {
r: this.expandChannel(quantized.r, rBits),
g: this.expandChannel(quantized.g, gBits),
b: this.expandChannel(quantized.b, bBits)
};
if (aBits && quantized.a !== undefined) {
expanded.a = this.expandChannel(quantized.a, aBits);
} else {
expanded.a = 255;
}
return expanded;
}
expandChannel(quantizedValue, bits) {
const maxQuantized = (1 << bits) - 1;
return Math.round((quantizedValue / maxQuantized) * 255);
}
applySRGBGamma(linearValue) {
return linearValue <= 0.0031308 ?
12.92 * linearValue :
1.055 * Math.pow(linearValue, 1 / 2.4) - 0.055;
}
removeSRGBGamma(gammaValue) {
return gammaValue <= 0.04045 ?
gammaValue / 12.92 :
Math.pow((gammaValue + 0.055) / 1.055, 2.4);
}
assessQuantizationQuality(original, quantized) {
// Calculate color difference after quantization
const originalExpanded = this.expandColor(quantized, { r: 8, g: 8, b: 8, alpha: 8 });
const deltaR = Math.abs(original.r - originalExpanded.r);
const deltaG = Math.abs(original.g - originalExpanded.g);
const deltaB = Math.abs(original.b - originalExpanded.b);
const totalError = deltaR + deltaG + deltaB;
const maxError = 255 * 3;
const quality = 1 - (totalError / maxError);
return {
quality: Math.max(0, Math.min(1, quality)),
error: totalError,
grade: this.gradeQuantizationQuality(quality)
};
}
gradeQuantizationQuality(quality) {
if (quality > 0.99) return 'Excellent';
if (quality > 0.95) return 'Very Good';
if (quality > 0.90) return 'Good';
if (quality > 0.80) return 'Acceptable';
return 'Poor';
}
// Analyze encoding efficiency
analyzeEncodingEfficiency(colors, format) {
const formatSpec = this.encodingFormats[format];
const results = colors.map(color => this.encodeColor(color, format));
const qualities = results.map(r => r.quality.quality);
const avgQuality = qualities.reduce((sum, q) => sum + q, 0) / qualities.length;
const uniqueColors = new Set(results.map(r => r.packed)).size;
const colorUtilization = uniqueColors / Math.pow(2, formatSpec.bits);
return {
format,
bitDepth: formatSpec.bits,
averageQuality: Math.round(avgQuality * 1000) / 1000,
uniqueColors,
totalPossibleColors: Math.pow(2, formatSpec.bits),
colorUtilization: Math.round(colorUtilization * 1000) / 1000,
efficiency: this.calculateEfficiencyScore(avgQuality, colorUtilization),
recommendations: this.generateEncodingRecommendations(avgQuality, colorUtilization, formatSpec)
};
}
calculateEfficiencyScore(quality, utilization) {
// Balance between quality and efficient use of available colors
const qualityWeight = 0.7;
const utilizationWeight = 0.3;
return Math.round((quality * qualityWeight + utilization * utilizationWeight) * 100);
}
generateEncodingRecommendations(quality, utilization, formatSpec) {
const recommendations = [];
if (quality < 0.9) {
recommendations.push(`Quality is ${Math.round(quality * 100)}% - consider higher bit depth`);
}
if (utilization < 0.1) {
recommendations.push('Low color utilization - consider lower bit depth for efficiency');
} else if (utilization > 0.8) {
recommendations.push('High color utilization - format is well-suited for this content');
}
if (formatSpec.bits >= 32) {
recommendations.push('High bit depth format - ensure target supports this precision');
}
return recommendations;
}
// Compare different encoding formats
compareEncodingFormats(testColors, formats = null) {
const testFormats = formats || Object.keys(this.encodingFormats);
const comparisons = testFormats.map(format => {
const analysis = this.analyzeEncodingEfficiency(testColors, format);
// Calculate storage requirements
const bitsPerPixel = this.encodingFormats[format].bits;
const bytesPerPixel = Math.ceil(bitsPerPixel / 8);
const totalBytes = testColors.length * bytesPerPixel;
return {
...analysis,
storage: {
bitsPerPixel,
bytesPerPixel,
totalBytes,
compressionRatio: (testColors.length * 3) / totalBytes // vs 24-bit RGB
}
};
});
// Sort by efficiency score
comparisons.sort((a, b) => b.efficiency - a.efficiency);
return {
testColors: testColors.length,
comparisons,
recommendations: this.generateFormatRecommendations(comparisons)
};
}
generateFormatRecommendations(comparisons) {
const recommendations = [];
const best = comparisons[0];
recommendations.push(`Best overall format: ${best.format} (${best.efficiency}% efficiency)`);
const highQuality = comparisons.filter(c => c.averageQuality > 0.95);
if (highQuality.length > 0) {
recommendations.push(`Highest quality: ${highQuality[0].format} (${Math.round(highQuality[0].averageQuality * 100)}% quality)`);
}
const mostEfficient = comparisons.reduce((min, c) =>
c.storage.bytesPerPixel < min.storage.bytesPerPixel ? c : min
);
recommendations.push(`Most storage efficient: ${mostEfficient.format} (${mostEfficient.storage.bytesPerPixel} bytes/pixel)`);
return recommendations;
}
// HDR color encoding
encodeHDRColor(color, format = 'rgb101010') {
// HDR colors may have values > 1.0
const { r, g, b, a = 1.0 } = color;
// Apply tone mapping for display
const toneMapped = this.applyToneMapping({ r, g, b }, 'reinhard');
// Encode with higher precision
const encoded = this.encodeColor(
{
r: Math.round(toneMapped.r * 255),
g: Math.round(toneMapped.g * 255),
b: Math.round(toneMapped.b * 255),
a: Math.round(a * 255)
},
format
);
return {
...encoded,
hdr: true,
originalRange: { r, g, b, a },
toneMapped
};
}
applyToneMapping(hdrColor, method = 'reinhard') {
const { r, g, b } = hdrColor;
switch (method) {
case 'reinhard':
return {
r: r / (1 + r),
g: g / (1 + g),
b: b / (1 + b)
};
case 'aces':
const a = 2.51;
const b_coeff = 0.03;
const c = 2.43;
const d = 0.59;
const e = 0.14;
return {
r: Math.max(0, (r * (a * r + b_coeff)) / (r * (c * r + d) + e)),
g: Math.max(0, (g * (a * g + b_coeff)) / (g * (c * g + d) + e)),
b: Math.max(0, (b * (a * b + b_coeff)) / (b * (c * b + d) + e))
};
default:
return { r: Math.min(1, r), g: Math.min(1, g), b: Math.min(1, b) };
}
}
// Color space conversion for encoding
convertColorSpaceForEncoding(color, sourceSpace, targetSpace) {
// Simplified color space conversion
if (sourceSpace === targetSpace) {
return color;
}
// Convert through XYZ as intermediate space
const xyz = this.colorSpaceToXYZ(color, sourceSpace);
return this.xyzToColorSpace(xyz, targetSpace);
}
colorSpaceToXYZ(color, colorSpace) {
// Simplified conversion - would use proper matrices in practice
const { r, g, b } = color;
switch (colorSpace) {
case 'srgb':
return {
x: 0.4124 * r + 0.3576 * g + 0.1805 * b,
y: 0.2126 * r + 0.7152 * g + 0.0722 * b,
z: 0.0193 * r + 0.1192 * g + 0.9505 * b
};
case 'adobe-rgb':
return {
x: 0.5767 * r + 0.1856 * g + 0.1882 * b,
y: 0.2974 * r + 0.6273 * g + 0.0753 * b,
z: 0.0270 * r + 0.0707 * g + 0.9911 * b
};
default:
return { x: r, y: g, z: b };
}
}
xyzToColorSpace(xyz, colorSpace) {
const { x, y, z } = xyz;
switch (colorSpace) {
case 'srgb':
return {
r: 3.2406 * x - 1.5372 * y - 0.4986 * z,
g: -0.9689 * x + 1.8758 * y + 0.0415 * z,
b: 0.0557 * x - 0.2040 * y + 1.0570 * z
};
case 'adobe-rgb':
return {
r: 2.0414 * x - 0.5649 * y - 0.3447 * z,
g: -0.9693 * x + 1.8760 * y + 0.0416 * z,
b: 0.0134 * x - 0.1184 * y + 1.0154 * z
};
default:
return { r: x, g: y, b: z };
}
}
}Explore these comprehensive pillar articles related to Color Encoding
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
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.
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.
Discover more about Color Encoding and related color theory concepts
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.
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
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.
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.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary