<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Mended Photo Engineering]]></title><description><![CDATA[Mended Photo Engineering]]></description><link>https://mendedphoto.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 00:02:04 GMT</lastBuildDate><atom:link href="https://mendedphoto.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Detecting Faded 1970s Magenta Casts and Polaroid Dye Decay Client-Side with HTML5 Canvas Histograms]]></title><description><![CDATA[When users upload scanned 1960s through 1990s family photographs to a web restoration studio, a surprising share of "faded" prints are actually suffering…]]></description><link>https://mendedphoto.hashnode.dev/detecting-faded-1970s-magenta-casts-and-polaroid-dye-decay-client-side-with-html5-canvas-histograms</link><guid isPermaLink="true">https://mendedphoto.hashnode.dev/detecting-faded-1970s-magenta-casts-and-polaroid-dye-decay-client-side-with-html5-canvas-histograms</guid><category><![CDATA[Web Development]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5 Canvas]]></category><dc:creator><![CDATA[Miles Thorne]]></dc:creator><pubDate>Fri, 04 Dec 2026 14:24:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0c3d95b15a3e91c3b7d3a6/b090cb34-eb09-4be0-ba7e-27be57078ed7.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>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:</p>
<ul>
<li><strong>1970s Kodak/Ektachrome prints</strong> lose cyan dye first, pushing neutral grays and shadows sharply toward magenta/red.</li>
<li><strong>1970s–1990s Polaroid SX-70, 600, and Spectra instant prints</strong> often shift warm sepia/yellow or muddy green while crushing shadow contrast.</li>
<li><strong>Flatbed scans captured through picture frame glass</strong> introduce specular highlight spikes at <code>250..255</code> right over faces or dark jackets.</li>
</ul>
<p>Running a lightweight RGB channel diagnostic directly in the browser with HTML5 <code>&lt;canvas&gt;</code> 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.</p>
<h2>1. Downsample onto an offscreen canvas safely</h2>
<p>Analyzing a 40-megapixel TIFF pixel by pixel on the main thread stalls the UI. A <code>512px</code> 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.</p>
<pre><code class="language-ts">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&lt;PhotoDiagnostic&gt; {
  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);
}
</code></pre>
<h2>2. Ignore white scan borders and Polaroid frames</h2>
<p>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 <code>245</code> and hides severe dye decay inside the photo itself.</p>
<p>Sampling an inner <code>76%</code> crop window (<code>12%</code> inset on all four sides) avoids white scanner borders and Polaroid margins cleanly without requiring a heavy edge-detection model:</p>
<pre><code class="language-ts">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 &lt; y1; y++) {
    for (let x = x0; x &lt; 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 &gt;= 252 &amp;&amp; g &gt;= 252 &amp;&amp; b &gt;= 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 &lt; 115,
  };
}

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

function round1(n: number): number {
  return Math.round(n * 10) / 10;
}
</code></pre>
<h2>3. Classify chromogenic dye decay vs. neutral grayscale</h2>
<p>In physical film prints, different dye failures leave distinct signatures in mean channel separation:</p>
<pre><code class="language-ts">function classifyDyeCast(
  r: number,
  g: number,
  b: number
): PhotoDiagnostic['likelyCast'] {
  const spread = Math.max(r, g, b) - Math.min(r, g, b);
  if (spread &lt; 9) return 'neutral_or_bw';

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

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

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

  return 'neutral_or_bw';
}
</code></pre>
<h2>4. Why pair histogram diagnostics with pixel-dimension DPI checks?</h2>
<p>In practice, browser-side diagnostics are most helpful right at upload time when you combine two signals before any restoration starts:</p>
<ol>
<li><strong>Color-cast &amp; glare warning:</strong> If <code>clippedHighlightRatio &gt; 0.08</code>, 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).</li>
<li><strong>Print resolution readiness:</strong> Checking <code>bitmap.width</code> and <code>bitmap.height</code> locally against a 300-DPI framing target (<code>2400 x 3000 px</code> for an <code>8x10</code>) lets users know immediately whether their scan has enough source pixels for clean enlargement.</li>
</ol>
<p>We use this exact client-side inspection pattern at <strong>Mended Photo</strong> across our <a href="https://www.mendedphoto.com/photo-print-dpi-calculator?utm_source=hashnode&amp;utm_medium=organic&amp;utm_campaign=canvas_histogram_article">browser-local 300-DPI print &amp; scan calculator</a>, our <a href="https://www.mendedphoto.com/fix-faded-1970s-magenta-color-photos?utm_source=hashnode&amp;utm_medium=organic&amp;utm_campaign=canvas_histogram_article">1970s magenta color fade restoration guide</a>, and our <a href="https://www.mendedphoto.com/fix-faded-polaroid-photos?utm_source=hashnode&amp;utm_medium=organic&amp;utm_campaign=canvas_histogram_article">faded Polaroid restoration workflow</a>.</p>
<p>Running the diagnostic on <code>OffscreenCanvas</code> 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.</p>
]]></content:encoded></item><item><title><![CDATA[Building an Edge-Native 300-DPI Print and Framing PDF Pipeline in TypeScript]]></title><description><![CDATA[When people restore an old family photograph online, getting a sharp image on a laptop screen is only half the job. The real moment of truth happens two…]]></description><link>https://mendedphoto.hashnode.dev/building-an-edge-native-300-dpi-print-and-framing-pdf-pipeline-in-typescript</link><guid isPermaLink="true">https://mendedphoto.hashnode.dev/building-an-edge-native-300-dpi-print-and-framing-pdf-pipeline-in-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Cloudflare Workers]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Photography]]></category><dc:creator><![CDATA[Miles Thorne]]></dc:creator><pubDate>Tue, 01 Dec 2026 15:24:51 GMT</pubDate><content:encoded><![CDATA[<p>When people restore an old family photograph online, getting a sharp image on a laptop screen is only half the job. The real moment of truth happens two hours later when they upload that file to Walgreens Photo, CVS Photo, Walmart, or a local frame shop and pick up a physical 8x10 print.</p>
<p>In practice, two engineering details ruin more restored family prints than the restoration model itself: <strong>aspect-ratio head cropping</strong> and <strong>hidden JPEG compression at below 200 DPI</strong>.</p>
<p>While building <a href="https://www.mendedphoto.com/?utm_source=hashnode&amp;utm_medium=organic&amp;utm_campaign=print_dpi_engineering">Mended Photo</a>, I wanted every unlocked restoration to ship not just a 4K master file, but exact 300-DPI framing PDFs (<code>5x7"</code>, <code>8x10"</code>, <code>11x14"</code>, folded greeting cards, and multi-page family albums) generated directly inside a Cloudflare Worker in TypeScript, with zero native ImageMagick or headless Chrome binaries.</p>
<h2>Why Retail Kiosks Slice Off Foreheads on 8x10 Prints</h2>
<p>Classic 35mm family snapshots and modern phone cameras shoot at a <strong>2:3</strong> or <strong>3:4</strong> aspect ratio. A traditional <strong>8x10</strong> portrait frame is <strong>4:5</strong>, which is noticeably squarer:</p>
<ul>
<li><strong>4x6" (2:3):</strong> <code>1200 x 1800 px</code> at 300 DPI (minimal crop on 35mm film)</li>
<li><strong>5x7" (5:7):</strong> <code>1500 x 2100 px</code> at 300 DPI (~5% trimmed from the long edge)</li>
<li><strong>8x10" (4:5):</strong> <code>2400 x 3000 px</code> at 300 DPI (~17% trimmed from a 2:3 snapshot)</li>
<li><strong>11x14" (11:14):</strong> <code>3300 x 4200 px</code> at 300 DPI (requires a true 4K master to stay crisp)</li>
</ul>
<p>When a shopper drops a 2:3 vintage portrait onto a 4:5 retail kiosk template, the kiosk defaults to a centered "fill frame" zoom. Because vintage portraits place subjects' heads near the upper third, centered auto-cropping routinely clips hairlines, hats, or chins.</p>
<h2>Generating Exact 300-DPI Framing PDFs in TypeScript with <code>pdf-lib</code></h2>
<p>Because edge workers have tight memory and CPU budgets, spawning Chromium or shelling out to Ghostscript is out of the question. Instead, we generate clean single-page and multi-page archival PDFs directly in TypeScript using <code>pdf-lib</code>:</p>
<ol>
<li><strong>Exact physical point coordinates (<code>72 pt = 1 inch</code>):</strong> An <code>8x10"</code> sheet is created at exactly <code>576 x 720 pt</code>, an <code>11x14"</code> at <code>792 x 1008 pt</code>, and a <code>5x7"</code> at <code>360 x 504 pt</code>.</li>
<li><strong>Lossless or high-quality image embedding without downscaling:</strong> The 4K master (<code>3584 x 4800 px</code> or native orientation) is embedded at full pixel resolution inside the target image box so the effective print density stays at or above 300 DPI even at 11x14".</li>
<li><strong>Optional archival museum mat border:</strong> For tight vintage portraits where cropping 17% would cut a relative's forehead or shoulder, adding a crisp white archival mat border preserves 100% of the original scan inside a standard 8x10 frame with zero head cropping.</li>
<li><strong>Chunked SQLite storage for 4K masters:</strong> Restored 4K masters are stored in 450 KB SQLite binary chunks and streamed back cleanly on demand so edge workers never hit row-size caps.</li>
</ol>
<p>We also ship a free, browser-local <a href="https://www.mendedphoto.com/photo-print-dpi-calculator?utm_source=hashnode&amp;utm_medium=organic&amp;utm_campaign=print_dpi_engineering">300-DPI Photo Print Size Calculator</a> that inspects any local JPEG, PNG, WebP, TIFF, or HEIC in the browser without uploading it, showing exact maximum print sizes at 300 DPI and 200 DPI before anyone spends a dollar at a print counter.</p>
<h2>Practical Guides for Enlarging and Printing Old Family Scans</h2>
<p>If you are working on restoring or printing family albums this month, we published two practical reference guides based on what trips people up most often:</p>
<ul>
<li><a href="https://www.mendedphoto.com/print-restored-photos-walgreens-cvs?utm_source=hashnode&amp;utm_medium=organic&amp;utm_campaign=print_dpi_engineering">CVS &amp; Walgreens Photo Restoration and Same-Day Print Guide</a> — what retail photo counters handle in store vs. restoring at home first, exact 300-DPI pixel sizes, and why matte paper looks far better than gloss on 1940s–1970s portraits.</li>
<li><a href="https://www.mendedphoto.com/enlarge-old-photos-for-printing?utm_source=hashnode&amp;utm_medium=organic&amp;utm_campaign=print_dpi_engineering">How to Enlarge Small Wallet Photos to 8x10 Framed Prints</a> — how flatbed scan DPI (<code>600</code> vs <code>1200 DPI</code>) determines how far a 2x3" wallet print can safely scale without blocky facial detail.</li>
</ul>
<p>Anyone can test Mended Photo on their own scan or phone picture with a free before-and-after preview in ~20 seconds before paying anything; unlocked 4K masters and 300-DPI framing PDFs use simple one-time packs starting at $4.99 with no recurring subscription.</p>
]]></content:encoded></item><item><title><![CDATA[Extracting Embedded Photographs From Home-Scanner PDFs, 16-Bit TIFFs, and iPhone HEICs Locally in the Browser]]></title><description><![CDATA[If you build a web app that accepts real-world family photographs, you learn within 48 hours of launch that everyday users do not upload clean 1 MB sRGB…]]></description><link>https://mendedphoto.hashnode.dev/extracting-embedded-photographs-from-home-scanner-pdfs-16-bit-tiffs-and-iphone-heics-locally-in-the-browser</link><guid isPermaLink="true">https://mendedphoto.hashnode.dev/extracting-embedded-photographs-from-home-scanner-pdfs-16-bit-tiffs-and-iphone-heics-locally-in-the-browser</guid><category><![CDATA[Cloudflare Workers]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Photography]]></category><dc:creator><![CDATA[Miles Thorne]]></dc:creator><pubDate>Sun, 29 Nov 2026 15:02:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0c3d95b15a3e91c3b7d3a6/704aa2f8-8734-4801-a029-ea18885b36f2.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you build a web app that accepts real-world family photographs, you learn within 48 hours of launch that everyday users do not upload clean 1 MB sRGB JPEGs.</p>
<p>Three real files hit our upload dropzone at <a href="https://www.mendedphoto.com/?utm_source=hashnode&amp;utm_medium=referral&amp;utm_campaign=browser_decoding_guide">Mended Photo</a> right away:</p>
<ol>
<li><strong>50 MB uncompressed 16-bit TIFFs</strong> straight off Epson and Canon flatbed scanners.</li>
<li><strong>Apple HEIC photos</strong> shot on iPhones in portrait orientation with EXIF rotation flags.</li>
<li><strong>2.8 MB <code>.pdf</code> files</strong> produced when someone clicks "Scan" on an HP, Brother, Canon, or Epson home all-in-one printer-scanner (which defaults to PDF instead of JPEG) or uploads a misnamed file whose extension does not match its bytes.</li>
</ol>
<p>Sending raw 50 MB archival scans through serverless edge workers causes memory spikes, timeouts, and brittle server-side native binary dependencies. Instead, we built a pure browser-local ingestion pipeline that sniffs magic bytes, decodes TIFF, HEIC, and embedded scanner PDF rasters directly on the user's device, normalizes EXIF orientation and color space, and hands a clean working frame to the studio.</p>
<h2>1. Sniffing magic bytes before trusting filenames</h2>
<p>Home scanners and email clients frequently misname files (for example saving a HEIC or TIFF payload with a <code>.jpg</code> extension, or dropping a PDF without a MIME header). Before looking at <code>file.type</code> or <code>file.name</code>, inspect the first 16 bytes directly in the browser:</p>
<ul>
<li><code>FF D8 FF</code> -&gt; JPEG</li>
<li><code>89 50 4E 47</code> -&gt; PNG</li>
<li><code>25 50 44 46 2D</code> (<code>%PDF-</code>) -&gt; PDF</li>
<li><code>49 49 2A 00</code> or <code>4D 4D 00 2A</code> -&gt; TIFF (little-endian or big-endian)</li>
<li><code>ftyp</code> box at bytes 4..7 matching <code>heic</code>, <code>heix</code>, <code>mif1</code>, or <code>msf1</code> -&gt; HEIC/HEIF</li>
</ul>
<p>This takes microseconds, runs entirely offline, and rescues misnamed files before the browser's native <code>createImageBitmap</code> ever throws a cryptic decode error.</p>
<h2>2. Lazy-loading TIFF and HEIC decoders only when needed</h2>
<p>Shipping heavy decoders in the initial page bundle slows down every visitor who just drops a normal JPEG. We dynamically import <code>utif2</code> (for 8-bit and 16-bit uncompressed/LZW TIFFs) and <code>heic-to</code> (for Apple HEIC containers) inside <code>try/catch</code> branches only when magic-byte sniffing detects those formats.</p>
<h2>3. Pure client-side scanned PDF photo extraction without PDF.js</h2>
<p>When a home all-in-one printer saves a scanned photo as <code>Scan0001.pdf</code>, it almost never draws vector text. It wraps the scanned photograph inside a PDF Image XObject stream (<code>/Subtype /Image</code>).</p>
<p>Rather than bundling multi-megabyte PDF.js workers, we walk the first few pages using <code>pdf-lib</code> + <code>fflate</code> (both lazy-loaded on demand) and look for the largest embedded Image XObject by pixel area:</p>
<ul>
<li><strong><code>/DCTDecode</code> streams:</strong> The raw stream bytes are already a complete embedded JPEG. Wrapping them in <code>new Blob([bytes], { type: 'image/jpeg' })</code> yields the original scanner JPEG with zero recompression loss.</li>
<li><strong><code>/FlateDecode</code> streams:</strong> Decompress with <code>fflate.unzlibSync</code> (falling back to <code>inflateSync</code>), apply PNG row unfiltering (<code>Sub</code>, <code>Up</code>, <code>Average</code>, <code>Paeth</code>) when <code>/DecodeParms /Predictor &gt;= 10</code> is present, and convert <code>DeviceRGB</code>, <code>DeviceGray</code>, or <code>DeviceCMYK</code> channels directly into an HTML <code>&lt;canvas&gt;</code> <code>ImageData</code> buffer.</li>
</ul>
<p>Because the scanner PDF extraction runs inside the browser, it also powers our zero-upload <a href="https://www.mendedphoto.com/photo-print-dpi-calculator?utm_source=hashnode&amp;utm_medium=referral&amp;utm_campaign=browser_decoding_guide">300-DPI Photo Print &amp; Scanner Calculator</a>: drop any JPG, TIFF, HEIC, or scanner PDF and inspect exact pixel dimensions and maximum crisp framing size with zero bytes leaving your machine.</p>
<p>For archival flatbed scanning tips (including 600 DPI vs 1200 DPI wallet-print recommendations), read our full guide on <a href="https://www.mendedphoto.com/restore-tiff-dng-heic-photo-scans?utm_source=hashnode&amp;utm_medium=referral&amp;utm_campaign=browser_decoding_guide">restoring TIFF, DNG, and HEIC photo scans</a>.</p>
]]></content:encoded></item></channel></rss>