Skip to content

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

BMP export: Indexed Color documents save as palette BMPs

Sir Starch6dffa480acac
diff --git a/crates/codecs/README.md b/crates/codecs/README.md
index 7486d4650..5e76097db 100644
--- a/crates/codecs/README.md
+++ b/crates/codecs/README.md
@@ -65,6 +65,8 @@ the same.
Palette BMP and PNG pixels decode as RGB(A) in `Image`; `bmp_palette` and `png_palette` expose the
embedded table (and a PNG's transparent entry) so `photocraft-io` can open them in Indexed Color mode.
+`bmp_palette` returns the colours the header declares, not the decoder's 256-entry padding.
+`encode_bmp_indexed` writes the inverse: indices plus a table as an 8-bit palette BMP.
## Documented asymmetries and limitations
diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs
index 7e7eb76b2..286ef0270 100644
--- a/crates/codecs/src/codecs/via_image.rs
+++ b/crates/codecs/src/codecs/via_image.rs
@@ -34,7 +34,51 @@ fn map_err(f: Format, e: image::ImageError) -> CodecError {
pub(crate) fn bmp_palette(bytes: &[u8]) -> Result<Option<Vec<[u8; 3]>>, CodecError> {
let decoder = image::codecs::bmp::BmpDecoder::new(Cursor::new(bytes)).map_err(|e| map_err(Format::Bmp, e))?;
- Ok(decoder.get_palette().map(|palette| palette.to_vec()))
+ let mut palette = decoder.get_palette().map(|palette| palette.to_vec());
+ // The decoder always hands back 256 entries (it pads a short table with black to survive
+ // corrupt files); the file's own count is what the document's colour table should hold.
+ if let (Some(p), Some(n)) = (palette.as_mut(), bmp_palette_len(bytes)) {
+ p.truncate(n.max(1));
+ }
+ Ok(palette)
+}
+
+/// How many colours a palette BMP's header declares: `biClrUsed`, or 2^bits when it is 0.
+/// `None` for a header this does not recognise, which leaves the table as decoded.
+fn bmp_palette_len(bytes: &[u8]) -> Option<usize> {
+ let u16_at = |at: usize| bytes.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
+ let u32_at = |at: usize| bytes.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
+ let (bit_count, used) = match u32_at(14)? {
+ // OS/2 BITMAPCOREHEADER: no colour count, the bit depth sets the table size.
+ 12 => (u16_at(24)?, 0),
+ n if n >= 40 => (u16_at(28)?, u32_at(46)?),
+ _ => return None,
+ };
+ if !(1..=8).contains(&bit_count) {
+ return None;
+ }
+ let max = 1usize << bit_count;
+ Some(if used == 0 { max } else { (used as usize).min(max) })
+}
+
+/// Writes an 8-bit palette BMP: `indices` row-major, `palette` RGB entries (1..=256). The
+/// counterpart of [`bmp_palette`], for Indexed Color documents.
+pub(crate) fn encode_bmp_indexed(width: u32, height: u32, indices: &[u8], palette: &[[u8; 3]]) -> Result<Vec<u8>, CodecError> {
+ let f = Format::Bmp;
+ if width == 0 || height == 0 || u64::from(width) * u64::from(height) != indices.len() as u64 {
+ return Err(CodecError::InvalidImage("index data does not match the size".into()));
+ }
+ if palette.is_empty() || palette.len() > 256 {
+ return Err(CodecError::InvalidImage("a palette BMP holds 1 to 256 colours".into()));
+ }
+ if indices.iter().any(|&i| usize::from(i) >= palette.len()) {
+ return Err(CodecError::InvalidImage("palette index out of range".into()));
+ }
+ let mut out = Cursor::new(Vec::new());
+ image::codecs::bmp::BmpEncoder::new(&mut out)
+ .encode_with_palette(indices, width, height, image::ExtendedColorType::L8, Some(palette))
+ .map_err(|e| CodecError::encode(f, e))?;
+ Ok(out.into_inner())
}
/// The `image` decoder for `f` with our limits, its header read and its size checked.
@@ -178,3 +222,45 @@ pub(crate) fn encode(f: Format, src: &Image, plan: Plan, opts: &EncodeOptions) -
}
Ok(cursor.into_inner())
}
+
+#[cfg(test)]
+mod indexed_tests {
+ use super::*;
+
+ #[test]
+ fn palette_bmp_roundtrips_its_table_and_pixels() {
+ // 3 px wide: rows are padded to 4 bytes, so a wrong stride shows in the second row.
+ let pal = [[255, 0, 0], [0, 0, 255], [10, 20, 30]];
+ let idx = [0u8, 1, 2, 2, 1, 0];
+ let bytes = encode_bmp_indexed(3, 2, &idx, &pal).unwrap();
+ assert_eq!(bmp_palette(&bytes).unwrap().as_deref(), Some(&pal[..]), "the table survives, not a 256-entry grey ramp");
+ let img = decode(Format::Bmp, &bytes, &Limits::default()).unwrap();
+ assert_eq!(img.dimensions(), (3, 2));
+ let rgb = img.convert(ChannelLayout::Rgb, SampleType::U8);
+ let want: Vec<u8> = idx.iter().flat_map(|&i| pal[usize::from(i)]).collect();
+ assert_eq!(rgb.data(), want.as_slice());
+ }
+
+ #[test]
+ fn palette_len_follows_the_header() {
+ let mut bytes = encode_bmp_indexed(2, 1, &[0, 1], &[[1, 2, 3], [4, 5, 6]]).unwrap();
+ assert_eq!(bmp_palette_len(&bytes), Some(2));
+ // biClrUsed = 0 means the full 2^bits table.
+ bytes[46..50].copy_from_slice(&0u32.to_le_bytes());
+ assert_eq!(bmp_palette_len(&bytes), Some(256));
+ // A short or unknown header leaves the decoded table alone instead of panicking.
+ assert_eq!(bmp_palette_len(&bytes[..30]), None);
+ bytes[14..18].copy_from_slice(&7u32.to_le_bytes());
+ assert_eq!(bmp_palette_len(&bytes), None);
+ }
+
+ #[test]
+ fn palette_bmp_rejects_bad_input() {
+ let pal = [[0, 0, 0], [255, 255, 255]];
+ assert!(encode_bmp_indexed(3, 2, &[0; 5], &pal).is_err(), "size mismatch");
+ assert!(encode_bmp_indexed(0, 2, &[], &pal).is_err(), "empty");
+ assert!(encode_bmp_indexed(2, 1, &[0, 2], &pal).is_err(), "index past the table");
+ assert!(encode_bmp_indexed(1, 1, &[0], &[]).is_err(), "no colours");
+ assert!(encode_bmp_indexed(1, 1, &[0], &[[0; 3]; 257]).is_err(), "more than 256 colours");
+ }
+}
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 3831cf654..76f8b88f1 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -128,6 +128,12 @@ pub fn bmp_palette(bytes: &[u8]) -> Result<Option<Vec<[u8; 3]>>, CodecError> {
via_image::bmp_palette(bytes)
}
+/// Encodes `indices` (row-major, one byte per pixel) as an 8-bit palette BMP with the colour
+/// table `palette` (1 to 256 entries). Used for Indexed Color documents; BMP has no transparency.
+pub fn encode_bmp_indexed(width: u32, height: u32, indices: &[u8], palette: &[[u8; 3]]) -> Result<Vec<u8>, CodecError> {
+ via_image::encode_bmp_indexed(width, height, indices, palette)
+}
+
/// Lists the pages (image directories) of a TIFF or BigTIFF file without decoding pixels: the
/// main IFD chain and its SubIFDs, each with its size, kind (page, reduced-resolution copy or
/// mask) and storage. [`TiffInfo::default_page`] is the page [`decode`] opens.
diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs
index 54fe96090..492cbe80e 100644
--- a/crates/io/src/flat.rs
+++ b/crates/io/src/flat.rs
@@ -798,10 +798,10 @@ fn cmyk_image_to_srgb(img: &Image) -> Result<Image, IoError> {
Ok(Image::from_normalized(w, h, layout, sample, &out)?.with_icc(Some(dst.to_bytes().to_vec())).with_meta(img.meta.clone()))
}
-/// Indexed Color → PNG-8 with its colour table; Duotone → the inks rendered as RGB.
+/// Indexed Color → PNG-8 or an 8-bit BMP with its colour table; Duotone → the inks rendered as RGB.
fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) -> Result<Option<ExportResult>, IoError> {
match doc.mode {
- ColorMode::Indexed if format == Format::Png => {
+ ColorMode::Indexed if matches!(format, Format::Png | Format::Bmp) => {
let Some(table) = doc.color_table.as_ref().filter(|t| !t.colors.is_empty() && t.colors.len() <= 256) else { return Ok(None) };
let mut idx = try_buffer(doc.size.area() as usize, 1)?;
let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> {
@@ -811,6 +811,14 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) ->
}));
Ok(())
});
+ if format == Format::Bmp {
+ let bytes = codecs::encode_bmp_indexed(doc.size.width, doc.size.height, &idx, &table.colors)?;
+ let mut warnings = vec![format!("written as an 8-bit palette BMP ({} colours)", table.colors.len())];
+ if let Some(t) = table.transparent {
+ warnings.push(format!("BMP has no transparency; transparent pixels are written in the colour of palette entry {t}"));
+ }
+ return Ok(Some(ExportResult { bytes, warnings }));
+ }
// 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..3b9e6135c 100644
--- a/crates/io/tests/modes.rs
+++ b/crates/io/tests/modes.rs
@@ -49,3 +49,37 @@ fn indexed_png_keeps_the_document_resolution() {
let back = photocraft_io::import("x.png", &r.bytes).unwrap().document;
assert!((back.resolution_dpi - 300.0).abs() < 0.01, "{}", back.resolution_dpi);
}
+
+#[test]
+fn indexed_bmp_is_palette_bmp() {
+ // The BMP export wrote an Indexed Color document as 24-bit RGB, so reopening it lost the mode (#3869 follow-up).
+ let mut d = doc(ColorMode::Indexed);
+ d.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 0, 0], [0, 255, 0]], transparent: None });
+ let r = photocraft_io::export(&d, "x.bmp", &Default::default()).unwrap();
+ assert_eq!(u16::from_le_bytes([r.bytes[28], r.bytes[29]]), 8, "8 bits per pixel");
+ assert!(r.warnings.iter().any(|w| w.contains("palette BMP")), "{:?}", r.warnings);
+ let back = photocraft_io::import("x.bmp", &r.bytes).unwrap().document;
+ assert_eq!(back.mode, ColorMode::Indexed);
+ assert_eq!(back.color_table.as_ref().map(|t| t.colors.clone()), Some(vec![[0, 0, 0], [255, 0, 0], [0, 255, 0]]));
+ let px = back.layers[0].surface().unwrap().rgba(1, 1);
+ assert_eq!(&px[..3], &[1.0, 0.0, 0.0]);
+}
+
+#[test]
+fn indexed_bmp_warns_that_it_has_no_transparency() {
+ let mut d = doc(ColorMode::Indexed);
+ d.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 0, 0]], transparent: Some(0) });
+ let r = photocraft_io::export(&d, "x.bmp", &Default::default()).unwrap();
+ assert!(r.warnings.iter().any(|w| w.contains("no transparency")), "{:?}", r.warnings);
+}
+
+#[test]
+fn indexed_bmp_without_a_usable_table_falls_back_to_rgb() {
+ // No table (or one past 256 entries) keeps the old 24-bit path rather than failing the save.
+ for table in [None, Some(ColorTable { colors: vec![[0; 3]; 257], transparent: None })] {
+ let mut d = doc(ColorMode::Indexed);
+ d.color_table = table;
+ let r = photocraft_io::export(&d, "x.bmp", &Default::default()).unwrap();
+ assert_eq!(u16::from_le_bytes([r.bytes[28], r.bytes[29]]), 24);
+ }
+}
diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md
index 2651f4c4d..45c25964d 100644
--- a/docs/file-format-parity.md
+++ b/docs/file-format-parity.md
@@ -28,7 +28,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.
| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); no JPEG Options dialog (quality 0–12, baseline/progressive) (FILE-215-19) |
| PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804) |
| GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done |
-| BMP | R/W | yes | yes | 8-bit; palette BMPs open in Indexed Color mode |
+| BMP | R/W | yes | yes | 8-bit; palette BMPs open in Indexed Color mode and Indexed Color documents save as palette BMPs (no transparency) |
| WebP | R/W | yes | yes | Lossless and our own lossy VP8 encoder; ICC/EXIF/XMP; Save keeps an opened file lossy (at its quality) or lossless (#2399) |
| AVIF | R/W | no (#463) | optional feature, off by default | |
| JPEG XL | R/W | inside DNG only | no | |
@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
| Date | Change | Summary |
|---|---|---|
+| 2026-10-15 | minor | Indexed Color documents save as 8-bit palette BMPs with their colour table instead of 24-bit RGB; a palette BMP opens with its declared number of colours, not 256 |
| 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 |
| 2026-10-13 | minor | CMYK Hue/Saturation (not Colorize) and Color Balance work on C, M and Y as inverted RGB with black kept, on the inks for display, export and destructive edits; cmyk8/16 hue-saturation 100% → 0.4–0.7% bad pixels, color-balance 74% → 25% |
| 2026-10-13 | minor | CMYK Posterize works on the stored values (1 − ink), as Photoshop does: psd-tools posterize_cmyk passes (13.8 % → 0 of pixels off on the ink path); psd-tools floor → 242 of 309 |