Dev.to WebDev šŸ›  Dev šŸ‘ 0 šŸ“– 4 min read

Detecting Faded 1970s Magenta Casts and Polaroid Dye Decay Client-Side with HTML5 Canvas Histograms

When users upload scanned 1960s through 1990s family photographs to a web restoration studio, a surprising share of "faded" prints are actually suffering from predictable chromogenic dye decay: 1970s Kodak/Ektachrome

When users upload scanned 1960s through 1990s family photographs to a web restoration studio, a surprising share of "faded" prints are actually suffering from predictable chromogenic dye decay:

  • 1970s Kodak/Ektachrome prints lose cyan dye first, pushing neutral grays and shadows sharply toward magenta/red.
  • 1970s–1990s Polaroid SX-70, 600, and Spectra instant prints often shift warm sepia/yellow or muddy green while crushing shadow contrast.
  • Flatbed scans captured through picture frame glass introduce specular highlight spikes at 250..255 right over faces or dark jackets.

Running a lightweight RGB channel diagnostic directly in the browser with HTML5 <canvas> takes under 15 milliseconds on a downsampled proxy and requires zero server round-trips. Here is how to build a deterministic color-cast, contrast, and highlight-clipping detector in plain TypeScript.

1. Downsample onto an offscreen canvas safely

Analyzing a 40-megapixel TIFF pixel by pixel on the main thread stalls the UI. A 512px longest-edge canvas gives more than 200,000 samples, which is statistically rock-solid for channel percentiles and cast ratios while finishing in a few milliseconds.

export interface PhotoDiagnostic {
  meanR: number;
  meanG: number;
  meanB: number;
  p02Luma: number;
  p98Luma: number;
  clippedHighlightRatio: number;
  likelyCast: 'magenta_1970s' | 'warm_sepia_polaroid' | 'green_instant' | 'neutral_or_bw';
  lowContrast: boolean;
}

export async function analyzeImageFile(file: File): Promise<PhotoDiagnostic> {
  const bitmap = await createImageBitmap(file);
  const scale = Math.min(1, 512 / Math.max(bitmap.width, bitmap.height));
  const w = Math.max(1, Math.round(bitmap.width * scale));
  const h = Math.max(1, Math.round(bitmap.height * scale));

  const canvas = new OffscreenCanvas(w, h);
  const ctx = canvas.getContext('2d', { willReadFrequently: true });
  if (!ctx) throw new Error('2D context unavailable');

  ctx.drawImage(bitmap, 0, 0, w, h);
  bitmap.close();

  const { data } = ctx.getImageData(0, 0, w, h);
  return computeHistogramMetrics(data, w, h);
}

2. Ignore white scan borders and Polaroid frames

One subtle trap with scanned prints and vintage Polaroids is the bright white paper margin (or the thick Polaroid chin). If you average every pixel in the frame, a white scanner bed skews all three channels toward 245 and hides severe dye decay inside the photo itself.

Sampling an inner 76% crop window (12% inset on all four sides) avoids white scanner borders and Polaroid margins cleanly without requiring a heavy edge-detection model:

function computeHistogramMetrics(
  rgba: Uint8ClampedArray,
  width: number,
  height: number
): PhotoDiagnostic {
  const histLuma = new Uint32Array(256);
  const x0 = Math.floor(width * 0.12);
  const x1 = Math.ceil(width * 0.88);
  const y0 = Math.floor(height * 0.12);
  const y1 = Math.ceil(height * 0.88);

  let sumR = 0;
  let sumG = 0;
  let sumB = 0;
  let clipped = 0;
  let count = 0;

  for (let y = y0; y < y1; y++) {
    for (let x = x0; x < x1; x++) {
      const i = (y * width + x) * 4;
      const r = rgba[i];
      const g = rgba[i + 1];
      const b = rgba[i + 2];

      sumR += r;
      sumG += g;
      sumB += b;
      if (r >= 252 && g >= 252 && b >= 252) clipped++;

      const luma = Math.round(0.2126 * r + 0.7152 * g + 0.0722 * b);
      histLuma[luma]++;
      count++;
    }
  }

  const meanR = sumR / count;
  const meanG = sumG / count;
  const meanB = sumB / count;

  const p02Luma = percentileFromHist(histLuma, count, 0.02);
  const p98Luma = percentileFromHist(histLuma, count, 0.98);
  const dynamicRange = p98Luma - p02Luma;

  const likelyCast = classifyDyeCast(meanR, meanG, meanB);

  return {
    meanR: round1(meanR),
    meanG: round1(meanG),
    meanB: round1(meanB),
    p02Luma,
    p98Luma,
    clippedHighlightRatio: Number((clipped / count).toFixed(4)),
    likelyCast,
    lowContrast: dynamicRange < 115,
  };
}

function percentileFromHist(hist: Uint32Array, total: number, q: number): number {
  const target = total * q;
  let acc = 0;
  for (let v = 0; v < 256; v++) {
    acc += hist[v];
    if (acc >= target) return v;
  }
  return 255;
}

function round1(n: number): number {
  return Math.round(n * 10) / 10;
}

3. Classify chromogenic dye decay vs. neutral grayscale

In physical film prints, different dye failures leave distinct signatures in mean channel separation:

function classifyDyeCast(
  r: number,
  g: number,
  b: number
): PhotoDiagnostic['likelyCast'] {
  const spread = Math.max(r, g, b) - Math.min(r, g, b);
  if (spread < 9) return 'neutral_or_bw';

  // 1970s cyan-dye loss: red dominates strongly while green drops lowest
  if (r - g > 18 && b - g > 4) {
    return 'magenta_1970s';
  }

  // Aged Polaroid / warm yellow-brown drift: red and green well above blue
  if (r - b > 20 && g - b > 10) {
    return 'warm_sepia_polaroid';
  }

  // Muddy green shift common in aged integral instant film
  if (g - r > 10 && g - b > 10) {
    return 'green_instant';
  }

  return 'neutral_or_bw';
}

4. Why pair histogram diagnostics with pixel-dimension DPI checks?

In practice, browser-side diagnostics are most helpful right at upload time when you combine two signals before any restoration starts:

  1. Color-cast & glare warning: If clippedHighlightRatio > 0.08, warn the user that overhead ceiling glare or phone flash washed out highlight detail (especially common on glossy Mylar Polaroids and photos photographed behind frame glass).
  2. Print resolution readiness: Checking bitmap.width and bitmap.height locally against a 300-DPI framing target (2400 x 3000 px for an 8x10) lets users know immediately whether their scan has enough source pixels for clean enlargement.

We use this exact client-side inspection pattern at Mended Photo across our browser-local 300-DPI print & scan calculator, our 1970s magenta color fade restoration guide, and our faded Polaroid restoration workflow.

Running the diagnostic on OffscreenCanvas keeps private family scans strictly on the visitor's own machine during pre-check, catches phone-flash glare before wasting processing, and gives concrete feedback in milliseconds.

šŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.