diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 19907dc084..f5b4164f86 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -902,7 +902,9 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc // The colors mapped to transparent all become the one transparent entry, so together they take // one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of // them and no pixel is transparent, that slot goes to the next opaque color instead. - let ix = quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, true)); + let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true); + let mut ix = quantize::quantize_to(rgba, w, h, o, &kept); + clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear); if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) { return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false))); } @@ -929,6 +931,37 @@ fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: .collect() } +/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to +/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the +/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later. +fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) { + let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect(); + if dropped.is_empty() { + return; + } + let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); + let near = quantize::nearest_entries(rgba, o, &all); + if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) { + return; + } + let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) { + Some(i) => i, + None => { + // A kept color mapped to transparent that no pixel took; at most 255 entries are used then. + let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else { + return; + }; + ix.palette.push(*c); + i + } + }; + for (v, n) in ix.indices.iter_mut().zip(&near) { + if n.is_some_and(|n| n >= kept.len()) { + *v = entry; + } + } +} + /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). pub fn decode(o: &Optimized) -> std::result::Result<(Vec, u32, u32), String> { let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?; diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 9930e3e2fe..62dd4d8612 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -574,6 +574,16 @@ fn colour_table_fixed_palette_keeps_an_opaque_color() { let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}}); let img = pixels(&one(&mut s, p)); assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0)); + // With one opaque color and 255 mapped to transparent, the last of those does not fit, and its + // pixels still become transparent rather than taking the opaque color nearest them. + let mut d = session(30.0, 10.0); + rect(&mut d, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut d, [10.0, 0.0, 10.0, 10.0], "#0000ee"); + let clear: Vec = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect(); + let palette: Vec = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect(); + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}}); + let img = pixels(&one(&mut d, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0)); // Without transparent pixels the colors mapped to transparent still take one slot together. let mut t = session(30.0, 10.0); rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000"); diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index dc459d4331..fff66aa142 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -203,6 +203,21 @@ pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pal finish(px, &colors, width, height, &palette, o, o.dither) } +/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures +/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a +/// pixel that becomes transparent, and for every pixel when `palette` is empty. +pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { + let px = rgba.as_chunks::<4>().0; + let colors = opaque_colors(px, o, false); + let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); + let index = PaletteIndex::new(&pal, o.reduction.weights()); + colors + .iter() + .zip(px) + .map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) }) + .collect() +} + /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> { let matte = o.matte.unwrap_or([255; 3]);