Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(io): exclude transparent palette entries for opaque PNG pixels (#5869)

Jason Xiangc41a7957f9f7
diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs
index a18367467..674c60561 100644
--- a/crates/io/src/flat.rs
+++ b/crates/io/src/flat.rs
@@ -810,14 +810,24 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) ->
match doc.mode {
ColorMode::Indexed if format == Format::Png => {
let Some(table) = doc.color_table.as_ref().filter(|t| !t.colors.is_empty() && t.colors.len() <= 256) else { return Ok(None) };
+ // PNG transparency belongs to a palette index, not its RGB value. Keep the
+ // transparent entry out of opaque lookup, even when it duplicates an opaque colour.
+ let (opaque_indices, colors): (Vec<u8>, Vec<_>) =
+ table.colors.iter().copied().enumerate().filter(|(i, _)| Some(*i) != table.transparent.map(usize::from)).map(|(i, c)| (i as u8, c)).unzip();
+ let opaque = photocraft_doc::ColorTable { colors, transparent: None };
let mut idx = try_buffer(doc.size.area() as usize, 1)?;
- let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> {
- idx.extend(band.px.iter().map(|p| match table.transparent {
- Some(t) if p[3] < 0.5 => t,
- _ => table.nearest([p[0], p[1], p[2]]) as u8,
- }));
+ photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), IoError> {
+ for p in &band.px {
+ let i = match table.transparent {
+ Some(t) if p[3] < 0.5 => t,
+ _ => *opaque_indices
+ .get(opaque.nearest([p[0], p[1], p[2]]))
+ .ok_or_else(|| IoError::Unsupported("Indexed PNG palette has no opaque entry; add an opaque colour or convert to RGB".into()))?,
+ };
+ idx.push(i);
+ }
Ok(())
- });
+ })?;
// Same rule as the ordinary PNG encoder: the resolution goes into `pHYs` with the metadata.
let dpi = opts.encode.embed_metadata.then_some((doc.resolution_dpi, doc.resolution_dpi));
let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, dpi)?;
diff --git a/crates/io/tests/modes.rs b/crates/io/tests/modes.rs
index f33fe5927..c16676621 100644
--- a/crates/io/tests/modes.rs
+++ b/crates/io/tests/modes.rs
@@ -25,6 +25,109 @@ fn indexed_png_is_palette_png() {
assert!(!j.bytes.is_empty());
}
+#[test]
+fn indexed_png_keeps_duplicate_palette_colors_opaque() {
+ // PLTE entries may have identical RGB but different tRNS alpha. RGB-only lookup used to
+ // choose the first red entry for both pixels, making the opaque one disappear on save.
+ let palette = [[255, 0, 0], [0, 255, 0], [255, 0, 0], [0, 0, 255]];
+ for transparent in [0, 2] {
+ let png = photocraft_codecs::encode_png_indexed(4, 1, &[0, 1, 2, 3], &palette, Some(transparent), None).unwrap();
+ let d = photocraft_io::import("in.png", &png).unwrap().document;
+ assert_eq!(d.mode, ColorMode::Indexed);
+ let before = d.color_table.clone();
+ let r = photocraft_io::export(&d, "out.png", &Default::default()).unwrap();
+ let table = photocraft_codecs::png_palette(&r.bytes).unwrap().unwrap();
+ assert_eq!(table.colors, palette, "palette order must not change");
+ assert_eq!(table.transparent, Some(transparent));
+ assert_eq!(photocraft_codecs::decode(&r.bytes).unwrap().data(), photocraft_codecs::decode(&png).unwrap().data());
+ let back = photocraft_io::import("out.png", &r.bytes).unwrap().document;
+ assert_eq!(back.color_table, before);
+ assert_eq!(d.color_table, before, "export must not edit the document's table");
+ for x in 0..4 {
+ assert_eq!(back.layers[0].surface().unwrap().rgba(x, 0)[3], if x == i32::from(transparent) { 0.0 } else { 1.0 });
+ }
+ }
+}
+
+#[test]
+fn indexed_png_uses_the_nearest_opaque_color() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for transparent in [0, 1, 2] {
+ let mut palette = vec![[0, 0, 255], [255, 128, 0]];
+ palette.insert(usize::from(transparent), [255, 0, 0]);
+ let mut d = Document::with_background("m", Size::new(1, 1), ColorMode::Rgb, depth, Color::rgba(1.0, 0.0, 0.0, 1.0));
+ d.mode = ColorMode::Indexed;
+ d.color_table = Some(ColorTable { colors: palette.clone(), transparent: Some(transparent) });
+ let r = photocraft_io::export(&d, "out.png", &Default::default()).unwrap();
+ let image = photocraft_codecs::decode(&r.bytes).unwrap();
+ assert_eq!(image.data(), &[255, 128, 0, 255], "{depth:?}, transparent = {transparent}");
+ let table = photocraft_codecs::png_palette(&r.bytes).unwrap().unwrap();
+ assert_eq!(table.colors, palette);
+ assert_eq!(table.transparent, Some(transparent));
+ }
+ }
+}
+
+#[test]
+fn indexed_png_breaks_opaque_color_ties_in_palette_order() {
+ // Both opaque entries are equally far from magenta; the transparent entry is an exact
+ // match. Filtering transparency must still choose the earlier original opaque entry.
+ for opaque in [[[255, 0, 0], [0, 0, 255]], [[0, 0, 255], [255, 0, 0]]] {
+ let mut d = Document::with_background("m", Size::new(1, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(1.0, 0.0, 1.0, 1.0));
+ d.mode = ColorMode::Indexed;
+ d.color_table = Some(ColorTable { colors: vec![[255, 0, 255], opaque[0], opaque[1]], transparent: Some(0) });
+ let r = photocraft_io::export(&d, "out.png", &Default::default()).unwrap();
+ let image = photocraft_codecs::decode(&r.bytes).unwrap();
+ assert_eq!(image.data(), &[opaque[0][0], opaque[0][1], opaque[0][2], 255]);
+ }
+}
+
+#[test]
+fn indexed_png_keeps_the_alpha_threshold() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let mut d = Document::with_background("m", Size::new(3, 1), ColorMode::Rgb, depth, Color::rgba(1.0, 0.0, 0.0, 1.0));
+ d.mode = ColorMode::Indexed;
+ d.color_table = Some(ColorTable { colors: vec![[255, 0, 0], [255, 0, 0]], transparent: Some(0) });
+ let surface = d.layers[0].surface_mut().unwrap();
+ surface.write_pixel(0, 0, &[1.0, 0.0, 0.0, 0.49]);
+ surface.write_pixel(1, 0, &[1.0, 0.0, 0.0, 0.5]);
+ let r = photocraft_io::export(&d, "out.png", &Default::default()).unwrap();
+ assert_eq!(photocraft_codecs::decode(&r.bytes).unwrap().data(), &[255, 0, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255], "{depth:?}");
+ }
+}
+
+#[test]
+fn indexed_png_keeps_the_last_palette_index() {
+ let mut palette = vec![[0, 0, 255]; 256];
+ palette[0] = [255, 0, 0];
+ palette[255] = [255, 0, 0];
+ for transparent in [0, 255] {
+ let png = photocraft_codecs::encode_png_indexed(2, 1, &[0, 255], &palette, Some(transparent), None).unwrap();
+ let d = photocraft_io::import("in.png", &png).unwrap().document;
+ let r = photocraft_io::export(&d, "out.png", &Default::default()).unwrap();
+ assert_eq!(photocraft_codecs::png_palette(&r.bytes).unwrap(), photocraft_codecs::png_palette(&png).unwrap());
+ assert_eq!(photocraft_codecs::decode(&r.bytes).unwrap().data(), photocraft_codecs::decode(&png).unwrap().data());
+ }
+}
+
+#[test]
+fn indexed_png_keeps_a_single_transparent_entry() {
+ let png = photocraft_codecs::encode_png_indexed(2, 1, &[0, 0], &[[255, 0, 0]], Some(0), None).unwrap();
+ let d = photocraft_io::import("in.png", &png).unwrap().document;
+ let r = photocraft_io::export(&d, "out.png", &Default::default()).unwrap();
+ assert_eq!(photocraft_codecs::png_palette(&r.bytes).unwrap(), photocraft_codecs::png_palette(&png).unwrap());
+ assert_eq!(photocraft_codecs::decode(&r.bytes).unwrap().data(), photocraft_codecs::decode(&png).unwrap().data());
+}
+
+#[test]
+fn indexed_png_rejects_opaque_pixels_without_an_opaque_entry() {
+ let mut d = doc(ColorMode::Indexed);
+ d.color_table = Some(ColorTable { colors: vec![[255, 0, 0]], transparent: Some(0) });
+ let err = photocraft_io::export(&d, "out.png", &Default::default()).unwrap_err();
+ assert!(matches!(err, photocraft_io::IoError::Unsupported(_)), "{err}");
+ assert!(err.to_string().contains("no opaque entry"), "{err}");
+}
+
#[test]
fn duotone_exports_the_inks_as_rgb() {
// Mid gray background.