Fix Desaturated sRGB and Display-P3 Colors in Sharp WebP/AVIF
Sharp metadata check: input hasProfile=true (Display P3 / Adobe RGB) -> output WebP/AVIF hasProfile=false | Vermilion reds, oranges, and brand accents shift visibly dull and flat in browsers Your raw AI hero images from Midjourney V8, OpenAI GPT-Image-2.6, Adobe Firefly Image Model 5, or Figma Display-P3 exports look vibrant and punchy on macOS Preview and Figma, yet turn noticeably desaturated, muddy, or flat-orange the moment your Node.js sharp build script converts them to WebP or AVIF.
By default, sharp strips embedded ICC color profiles without converting pixel values out of wide-gamut Display P3 or Adobe RGB into sRGB—and calling .toColorspace("srgb") alone does not perform an ICC gamut transform, while default 4:2:0 chroma subsampling blurs saturated brand reds and thin editorial graphics.
Copy-Paste Verified Fix
#!/usr/bin/env bash
set -euo pipefail
# Usage: ./convert-color-safe-webp-avif.sh ./raw-pngs ./public/images [srgb|keep-p3]
# Requires Node 18+ and sharp >= 0.33 (which ships withIccProfile and keepIccProfile)
IN_DIR="${1:?Provide input directory of PNG/JPG masters}"
OUT_DIR="${2:?Provide output directory}"
COLOR_MODE="${3:-srgb}"
mkdir -p "$OUT_DIR"
node --input-type=module - "$IN_DIR" "$OUT_DIR" "$COLOR_MODE" << 'JSEOF'
import { readdirSync } from 'node:fs';
import { join, parse } from 'node:path';
import sharp from 'sharp';
const [inDir, outDir, colorMode] = process.argv.slice(2);
const files = readdirSync(inDir).filter((f) => /.(png|jpe?g|tiff?)$/i.test(f));
if (files.length === 0) {
console.error(`No raster images found in ${inDir}`);
process.exit(1);
}
for (const file of files) {
const src = join(inDir, file);
const { name } = parse(file);
const meta = await sharp(src).metadata();
const hasAlpha = Boolean(meta.hasAlpha);
// Build color-managed base pipeline: .rotate() respects EXIF orientation while stripping EXIF bloat
let base = sharp(src)
.rotate()
.resize({ width: 1400, withoutEnlargement: true });
if (colorMode === 'keep-p3' && meta.hasProfile) {
// Keep original Display P3 / wide-gamut ICC profile ONLY (no GPS/EXIF bloat)
base = base.keepIccProfile();
} else {
// Default universal web delivery: transform any embedded P3/AdobeRGB/CMYK profile into sRGB
base = base.withIccProfile('srgb');
}
const webpOut = join(outDir, `${name}.webp`);
const avifOut = join(outDir, `${name}.avif`);
const webpInfo = await base
.clone()
.webp({
quality: hasAlpha ? 90 : 86,
alphaQuality: 95,
smartSubsample: true,
effort: 5,
})
.toFile(webpOut);
const avifInfo = await base
.clone()
.avif({
quality: 64,
effort: 4,
chromaSubsampling: '4:4:4',
})
.toFile(avifOut);
console.log(
`OK ${file} (srcProfile=${meta.hasProfile}) -> ` +
`${name}.webp (${(webpInfo.size / 1024).toFixed(1)}KB) | ` +
`${name}.avif (${(avifInfo.size / 1024).toFixed(1)}KB) [mode=${colorMode}]`
);
}
JSEOF Before vs. After (Broken Pattern vs. Verified Fix)
// Strips Display P3 / Adobe RGB ICC profile while leaving raw P3 numbers untagged:
await sharp('hero-p3.png')
.resize(1280)
.toColorspace('srgb') // Does NOT run LittleCMS P3 -> sRGB gamut mapping!
.webp({ quality: 82 })
.toFile('hero-washed-out.webp'); // Option A: Universal web-safe sRGB (accurately transforms P3/AdobeRGB pixels -> sRGB)
await sharp('hero-p3.png')
.rotate()
.resize({ width: 1280, withoutEnlargement: true })
.withIccProfile('srgb')
.webp({ quality: 86, smartSubsample: true, effort: 5 })
.toFile('hero-srgb-accurate.webp');
// Option B: Wide-gamut P3 AVIF for brand hero art (preserves ICC + 4:4:4 chroma)
await sharp('hero-p3.png')
.rotate()
.resize({ width: 1280, withoutEnlargement: true })
.keepIccProfile()
.avif({ quality: 64, effort: 4, chromaSubsampling: '4:4:4' })
.toFile('hero-p3-444.avif'); Why this works: Calling .withIccProfile("srgb") invokes LittleCMS2 to remap Display P3 or Adobe RGB coordinates accurately into sRGB and embeds a compact ~480-byte sRGB profile, while smartSubsample and 4:4:4 preserve saturated red/orange edges.
Why This Failure Happens in Real Pipelines
A Display P3 pixel with RGB value (224, 68, 32) represents a substantially more saturated vermilion red than the identical numeric triplet (224, 68, 32) inside standard sRGB. When creative tools—macOS Screenshot, Photoshop, Lightroom, Figma P3 frames, or Adobe Firefly exports—save a PNG with an embedded Display P3 or Adobe RGB ICC profile, browsers rely on that embedded profile to map wide-gamut colors accurately onto every monitor.
When developers run a naive sharp(input).resize(1280).webp({ quality: 82 }).toFile(out) pipeline, sharp strips ALL metadata including the ICC profile by default to save bytes, leaving raw P3 pixel numbers completely untagged. Every browser immediately interprets untagged WebP and AVIF files as standard sRGB, collapsing wide-gamut reds, greens, and skin warmth by 20–25% in perceived saturation. Crucially, adding .toColorspace("srgb") alone does NOT solve this bug: in libvips/sharp, toColorspace() changes pixel band interpretation (such as 16-bit or CMYK to 3-channel RGB) rather than executing a LittleCMS ICC gamut conversion from Display P3 to sRGB.
A second compounding defect hits brand graphics, charts, and bold vermilion or crimson packshots: lossy WebP and default AVIF (chromaSubsampling: "4:2:0") downsample color channels to one-quarter pixel resolution. On sharp typography and vivid red packaging, 4:2:0 chroma averaging visibly dims strokes and adds muddy halos. Using sharp 0.33+ explicit ICC methods—.withIccProfile("srgb") for universal web sRGB consistency (or .keepIccProfile() when deliberately shipping wide-gamut P3 assets)—paired with WebP smartSubsample: true and AVIF chromaSubsampling: "4:4:4" for color-critical assets preserves exact brand fidelity without carrying bloated EXIF camera tags.
Step-by-Step Resolution & Verification
- 01
Audit source images for Display P3 or Adobe RGB embedded ICC profiles
Inspect raw PNGs via sharp(file).metadata() to check hasProfile and icc byte length. Exports from macOS Preview, Figma P3 frames, Photoshop, and Adobe Firefly routinely carry wide-gamut profiles.
- 02
Replace .withMetadata() or bare .toColorspace("srgb") with .withIccProfile("srgb")
Use .withIccProfile("srgb") for consistent cross-browser sRGB delivery across Windows, Android, and macOS—or .keepIccProfile() strictly when targeting modern P3 displays without shipping camera EXIF bloat.
- 03
Enable WebP smartSubsample and AVIF 4:4:4 chroma for saturated brand colors
Pass smartSubsample: true on WebP and chromaSubsampling: "4:4:4" on AVIF for UI diagrams, editorial charts, and vivid red/orange packaging so chroma compression never dulls sharp edges.
node --input-type=module -e 'import sharp from "sharp"; for (const p of process.argv.slice(1)) { const m = await sharp(p).metadata(); console.log(p, { format: m.format, width: m.width, height: m.height, space: m.space, hasProfile: m.hasProfile, iccBytes: m.icc?.length ?? 0 }); }' ./public/images/*.webp ./public/images/*.avif ./public/images/hero.webp { format: 'webp', width: 1400, height: 840, space: 'srgb', hasProfile: true, iccBytes: 480 } # hasProfile MUST be true How to Prevent This Error From Recurring
Standardize design-system exports on sRGB unless explicitly building a P3 hero showcase
Mixing untagged CSS hex tokens with Display P3 raster hero PNGs creates visible seam lines where image backgrounds meet page canvases.
Prefer .keepIccProfile() over .withMetadata() in sharp pipelines
Calling .withMetadata() preserves private GPS, camera serial numbers, and 40 KB XMP blocks alongside the ICC profile; .keepIccProfile() keeps only the ~500-byte color profile.
Fail CI builds when wide-gamut inputs lose ICC profiles silently
Add a quick sharp(out).metadata().hasProfile assertion to your image-build script so future sharp refactors never reintroduce washed-out thumbnails.
Troubleshooting FAQs
- Why did .toColorspace("srgb") in sharp still leave my Display P3 PNG looking desaturated?
- In sharp and libvips, toColorspace("srgb") converts the pixel storage interpretation (for example from 16-bit or greyscale to 8-bit 3-channel RGB) without running an ICC color-profile gamut conversion. You must call .withIccProfile("srgb") in sharp 0.33+ to remap Display P3 or Adobe RGB coordinates into sRGB accurately.
- How much extra file size does embedding an sRGB or P3 ICC profile add to a WebP image?
- Sharp’s built-in sRGB and P3 ICC profiles add roughly 480 to 560 bytes (0.5 KB) per file—completely negligible compared to a 70–150 KB hero image, while guaranteeing identical color rendering across Safari, Chrome, Firefox, and Windows displays.
- Should I use AVIF chromaSubsampling "4:4:4" on every photo on my site?
- Use 4:4:4 on product packaging with red/orange typography, brand charts, UI screenshots, and vivid editorial hero images where chroma bleeding is noticeable. For soft natural background photography, default 4:2:0 saves 15–25% file weight with minimal visual difference.
- Does .withIccProfile("srgb") also fix inverted or dark colors on CMYK JPEG/TIFF inputs?
- Yes. Passing a CMYK print master through .withIccProfile("srgb") performs a proper ICC CMYK-to-sRGB transform instead of a crude mathematical channel inversion, giving accurate web previews from print packaging files.
- What if an older repo is pinned to sharp 0.32 without .withIccProfile()?
- Upgrade to sharp 0.33+ (or 0.34.x) wherever Node 18+ is available. On legacy sharp 0.32, .pipelineColourspace("rgb16").toColorspace("srgb").withMetadata() preserves existing profiles, but only sharp 0.33+ provides the clean built-in .withIccProfile("srgb") and .keepIccProfile() APIs.