diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index dbd7dca4c..bcd42e4e8 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -43,7 +43,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< | TIFF | yes | yes | U8, U16, F32 | all six (CMYK, CMYK+A included) | yes | yes (tag 34675) | no | yes (tag 700) | yes | yes (Description, Make, Model, Software, DateTime, Artist, Copyright) | no | `tiff` | | WebP | yes | yes | U8 | RGB, RGBA | yes | yes | yes | yes | no | no | yes (VP8, when `webp_lossless` is off) | `image-webp` / built-in VP8 | | GIF | yes | yes | U8 | RGBA | 1-bit | no | no | no | no | no | yes (256-colour palette) | `image` | -| BMP | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` | +| BMP | yes | yes | U8 | RGB, RGBA | yes | no | no | no | yes (header pixels per metre) | no | no | `image` | | TGA | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | no | `image` (read) / built in (RLE write, one scanline per packet) | | ICO | yes | yes | U8 | RGBA (at most 256×256) | yes | no | no | no | no | no | no | `image` | | DDS | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | yes (BC1–BC3, when `EncodeOptions::dds` asks for one) | built in | @@ -79,7 +79,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. +`encode_bmp_indexed` writes the inverse: indices plus a table as an 8-bit palette BMP; +`encode_bmp_indexed_with_dpi` also writes a resolution in the header. ## Documented asymmetries and limitations diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index ef607d378..e2faaac4c 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -1,6 +1,7 @@ pub(crate) mod avif; #[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))] pub(crate) mod avif_decode; +pub(crate) mod bmp; pub(crate) mod dds; pub(crate) mod dds_bc; pub(crate) mod deep_exr; diff --git a/crates/image-codecs/src/codecs/bmp.rs b/crates/image-codecs/src/codecs/bmp.rs new file mode 100644 index 000000000..239794a2c --- /dev/null +++ b/crates/image-codecs/src/codecs/bmp.rs @@ -0,0 +1,106 @@ +//! A BMP's resolution: `biXPelsPerMeter` and `biYPelsPerMeter`, the pixels per metre of the +//! BITMAPINFOHEADER and every later header (V4, V5, OS/2 2.x), at file offsets 38 and 42. The +//! 12-byte BITMAPCOREHEADER of OS/2 1.x has no such fields. The `image` crate reads and writes +//! the pixels only, and writes 0 here, which readers take as "no resolution". + +use super::png::dpi_of_ppm; + +/// Bytes before the fields: the 14-byte BITMAPFILEHEADER, then the DIB header's size, width, +/// height, planes, bit count, compression and image size. +const X_PPM: usize = 38; +const Y_PPM: usize = 42; +/// The shortest DIB header that carries the resolution (BITMAPINFOHEADER). +const INFO_HEADER: u32 = 40; +const METERS_PER_INCH: f64 = 0.0254; + +/// The little-endian 4 bytes at `at`, or `None` past the end of `bytes`. +fn le4(bytes: &[u8], at: usize) -> Option<[u8; 4]> { + bytes.get(at..at.checked_add(4)?)?.try_into().ok() +} + +/// Whether `bytes` start a BMP whose header has the resolution fields. +fn has_resolution_fields(bytes: &[u8]) -> bool { + bytes.starts_with(b"BM") && le4(bytes, Y_PPM).is_some() && le4(bytes, 14).map(u32::from_le_bytes).is_some_and(|dib| dib >= INFO_HEADER) +} + +/// The resolution in pixels per inch a BMP records, or `None` when its header has no fields for it +/// or either is 0 or negative (most writers leave them 0). A whole number of ppi stored rounded to +/// whole pixels per metre (300 ppi = 11811) reads back whole, as a PNG's `pHYs` does. +pub(crate) fn resolution(bytes: &[u8]) -> Option<(f32, f32)> { + if !has_resolution_fields(bytes) { + return None; + } + let field = |at: usize| le4(bytes, at).map(i32::from_le_bytes).and_then(|v| u32::try_from(v).ok()); + let (x, y) = (field(X_PPM)?, field(Y_PPM)?); + (x > 0 && y > 0).then(|| (dpi_of_ppm(x), dpi_of_ppm(y))) +} + +/// Pixels per metre for `ppi`, rounded as Photoshop and the PNG `pHYs` writer do (300 ppi = 11811), +/// or `None` for a resolution that has no positive whole number of pixels per metre. +fn ppm_of_dpi(ppi: f32) -> Option { + let ppm = (f64::from(ppi) / METERS_PER_INCH).round(); + (ppm.is_finite() && ppm >= 1.0).then(|| ppm.min(f64::from(i32::MAX)) as i32) +} + +/// Writes `dpi` into the resolution fields of the BMP in `bytes`. A header without the fields, or +/// a resolution that cannot be stored, leaves the bytes as they are. +pub(crate) fn set_resolution(bytes: &mut [u8], dpi: Option<(f32, f32)>) { + let Some((x, y)) = dpi.and_then(|(x, y)| Some((ppm_of_dpi(x)?, ppm_of_dpi(y)?))) else { return }; + if !has_resolution_fields(bytes) { + return; + } + for (at, ppm) in [(X_PPM, x), (Y_PPM, y)] { + if let Some(field) = bytes.get_mut(at..at + 4) { + field.copy_from_slice(&ppm.to_le_bytes()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 46-byte BMP start: file header, a DIB header of `dib` bytes, 11811 px/m each way. + fn start(dib: u32) -> Vec { + let mut b = vec![0u8; Y_PPM + 4]; + b[..2].copy_from_slice(b"BM"); + b[14..18].copy_from_slice(&dib.to_le_bytes()); + b[X_PPM..X_PPM + 4].copy_from_slice(&11811i32.to_le_bytes()); + b[Y_PPM..Y_PPM + 4].copy_from_slice(&11811i32.to_le_bytes()); + b + } + + #[test] + fn only_headers_with_the_fields_are_read_or_written() { + assert_eq!(resolution(&start(40)), Some((300.0, 300.0))); + assert_eq!(resolution(&start(124)), Some((300.0, 300.0)), "BITMAPV5HEADER"); + // OS/2 1.x's 12-byte core header has no resolution: those bytes are pixels or palette. + let mut core = start(12); + assert_eq!(resolution(&core), None); + set_resolution(&mut core, Some((72.0, 72.0))); + assert_eq!(core, start(12), "left as it is"); + // Too short, or not a BMP: nothing read, nothing written, no panic. + let mut short = start(40)[..Y_PPM + 3].to_vec(); + assert_eq!(resolution(&short), None); + set_resolution(&mut short, Some((72.0, 72.0))); + assert_eq!(short, start(40)[..Y_PPM + 3]); + let mut other = start(40); + other[0] = b'X'; + assert_eq!(resolution(&other), None); + set_resolution(&mut other, Some((72.0, 72.0))); + assert_eq!(&other[X_PPM..X_PPM + 4], &11811i32.to_le_bytes(), "not a BMP: left as it is"); + } + + #[test] + fn resolutions_without_a_whole_pixel_per_metre_are_not_written() { + for bad in [0.0, -300.0, 0.01, f32::NAN, f32::INFINITY] { + let mut b = start(40); + set_resolution(&mut b, Some((bad, 300.0))); + assert_eq!(b, start(40), "{bad}"); + } + // A huge one is capped at the field's maximum rather than wrapping negative. + let mut b = start(40); + set_resolution(&mut b, Some((1e12, 300.0))); + assert_eq!(&b[X_PPM..X_PPM + 4], &i32::MAX.to_le_bytes()); + } +} diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index 9e55dc3d2..983dab3dd 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -308,7 +308,8 @@ pub fn caps(format: Format) -> FormatCaps { // Resolution travels in EXIF (WebP has no field of its own). Format::WebP => FormatCaps { icc: true, exif: true, xmp: true, dpi: true, animation: true, ..base }, Format::Gif => FormatCaps { layouts: &[L::Rgba], animation: true, lossy: true, ..base }, - Format::Bmp => base, + // Resolution in the header's pixels per metre (BITMAPINFOHEADER and later). + Format::Bmp => FormatCaps { dpi: true, ..base }, Format::Tga => FormatCaps { layouts: RGB_GRAY, ..base }, Format::Ico => FormatCaps { layouts: &[L::Rgba], ..base }, Format::Pnm => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, ..base }, diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 24fd32deb..8c29ed52d 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -74,7 +74,7 @@ pub use half::f16; use crate::codecs::sgi; #[cfg(feature = "sunraster")] use crate::codecs::sunraster; -use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jpegls, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; +use crate::codecs::{bmp, dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jpegls, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; /// Detect the format and decode with default [`Limits`]. pub fn decode(bytes: &[u8]) -> Result { @@ -142,7 +142,11 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Avif => codecs::avif_decode::decode(bytes, l, opts.keep_orientation), #[cfg(not(all(feature = "avif-decode", not(target_arch = "wasm32"))))] Format::Avif => via_image::decode(format, bytes, l), - Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr => via_image::decode(format, bytes, l), + Format::Bmp => via_image::decode(format, bytes, l).map(|mut img| { + img.meta.dpi = bmp::resolution(bytes); + img + }), + Format::Gif | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr => via_image::decode(format, bytes, l), }?; finish_format(format, bytes, img, opts) } @@ -325,10 +329,26 @@ pub fn bmp_palette(bytes: &[u8]) -> Result>, CodecError> { /// 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. +/// The header's resolution is left unset; [`encode_bmp_indexed_with_dpi`] writes one. pub fn encode_bmp_indexed(width: u32, height: u32, indices: &[u8], palette: &[[u8; 3]]) -> Result, CodecError> { via_image::encode_bmp_indexed(width, height, indices, palette) } +/// [`encode_bmp_indexed`] with the resolution `dpi` (pixels per inch, horizontal then vertical) +/// in the header's pixels per metre, as [`encode`] writes [`Metadata::dpi`] for a BMP. `None`, or +/// a resolution with no positive whole number of pixels per metre, leaves the fields unset. +pub fn encode_bmp_indexed_with_dpi( + width: u32, + height: u32, + indices: &[u8], + palette: &[[u8; 3]], + dpi: Option<(f32, f32)>, +) -> Result, CodecError> { + let mut bytes = via_image::encode_bmp_indexed(width, height, indices, palette)?; + bmp::set_resolution(&mut bytes, dpi); + Ok(bytes) +} + /// 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. @@ -546,8 +566,12 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result Err(CodecError::unsupported(format, "encoding is not available in this build")), Format::Jp2 => Err(CodecError::unsupported(format, "JPEG 2000 is import-only; save as PNG or TIFF instead")), Format::Jxl => jxl::encode(image, plan), - Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => { - via_image::encode(format, image, plan, opts) - } + // The `image` crate leaves a BMP's resolution fields 0; Photoshop fills them in. They are + // part of the header, not metadata, so they are written whatever `embed_metadata` says. + Format::Bmp => via_image::encode(format, image, plan, opts).map(|mut bytes| { + bmp::set_resolution(&mut bytes, image.meta.dpi); + bytes + }), + Format::Gif | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::encode(format, image, plan, opts), } } diff --git a/crates/image-codecs/tests/it/bmp_resolution.rs b/crates/image-codecs/tests/it/bmp_resolution.rs new file mode 100644 index 000000000..2e35f222c --- /dev/null +++ b/crates/image-codecs/tests/it/bmp_resolution.rs @@ -0,0 +1,77 @@ +//! A BMP keeps its resolution in the header's `biXPelsPerMeter` and `biYPelsPerMeter`, which +//! Photoshop writes and reads (storytold/photocraft#13630). BMP exports left both 0, so a 300 ppi +//! document saved as BMP opened at 72 ppi elsewhere, and an opened BMP's resolution was ignored. + +use crate::common::test_image; +use craft_image_codecs::*; + +/// The DIB header's size and its pixels per metre, horizontal then vertical (file offsets 14, 38 +/// and 42, little-endian). +fn header(bytes: &[u8]) -> (u32, i32, i32) { + let at = |i: usize| [bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]; + (u32::from_le_bytes(at(14)), i32::from_le_bytes(at(38)), i32::from_le_bytes(at(42))) +} + +/// A test image of `layout` at resolution `dpi`. +fn image(layout: ChannelLayout, dpi: Option<(f32, f32)>) -> Image { + let mut img = test_image(layout, SampleType::U8); + img.meta.dpi = dpi; + img +} + +#[test] +fn bmp_export_writes_the_resolution_in_pixels_per_metre_and_reads_it_back() { + // RGB is written with a BITMAPINFOHEADER, RGBA with a BITMAPV4HEADER: same field offsets. + for (layout, dib) in [(ChannelLayout::Rgb, 40), (ChannelLayout::Rgba, 108)] { + // The fields are part of the header, not metadata: embed_metadata off keeps them. + for embed_metadata in [true, false] { + let opts = EncodeOptions { embed_metadata, ..Default::default() }; + let img = image(layout, Some((300.0, 150.0))); + let bytes = encode(&img, Format::Bmp, &opts).unwrap(); + // 300 / 0.0254 = 11811.02 and 150 / 0.0254 = 5905.51, rounded. + assert_eq!(header(&bytes), (dib, 11811, 5906), "{layout:?} metadata {embed_metadata}"); + assert_eq!(decode(&bytes).unwrap().meta.dpi, Some((300.0, 150.0)), "{layout:?} metadata {embed_metadata}"); + assert!(!fidelity_warnings_with(&img, Format::Bmp, &opts).contains(&FidelityWarning::DpiDropped), "{layout:?}"); + } + } +} + +#[test] +fn bmp_without_a_resolution_leaves_the_fields_unset() { + let bytes = encode(&image(ChannelLayout::Rgb, None), Format::Bmp, &EncodeOptions::default()).unwrap(); + assert_eq!(header(&bytes), (40, 0, 0)); + assert_eq!(decode(&bytes).unwrap().meta.dpi, None, "0 means no resolution: the caller's default applies"); +} + +#[test] +fn bmp_opens_at_the_resolution_its_header_records() { + let bytes = encode(&image(ChannelLayout::Rgb, None), Format::Bmp, &EncodeOptions::default()).unwrap(); + let with = |x: i32, y: i32| { + let mut b = bytes.clone(); + b[38..42].copy_from_slice(&x.to_le_bytes()); + b[42..46].copy_from_slice(&y.to_le_bytes()); + decode(&b).unwrap().meta.dpi + }; + // What other writers store for 96 and 72 ppi reads back whole. + assert_eq!(with(3780, 3780), Some((96.0, 96.0))); + assert_eq!(with(2835, 2835), Some((72.0, 72.0))); + // 40000 px/m is exactly 1016 ppi; a value no whole ppi rounds to stays as it is (71.98). + let (x, y) = with(40000, 2834).unwrap(); + assert_eq!(x, 1016.0); + assert!((y - 71.9836).abs() < 1e-3, "{y}"); + // An axis that is 0 or negative leaves the resolution unknown. + assert_eq!(with(11811, 0), None); + assert_eq!(with(-11811, 11811), None); +} + +#[test] +fn indexed_bmp_writes_the_resolution_it_is_given() { + let (idx, pal) = ([0u8, 1, 1, 0], [[0, 0, 0], [255, 0, 0]]); + let bytes = encode_bmp_indexed_with_dpi(2, 2, &idx, &pal, Some((300.0, 300.0))).unwrap(); + assert_eq!(header(&bytes), (40, 11811, 11811)); + assert_eq!(decode(&bytes).unwrap().meta.dpi, Some((300.0, 300.0))); + let unset = encode_bmp_indexed_with_dpi(2, 2, &idx, &pal, None).unwrap(); + assert_eq!(header(&unset), (40, 0, 0)); + // The existing function keeps writing no resolution, so its callers' files don't change. + assert_eq!(encode_bmp_indexed(2, 2, &idx, &pal).unwrap(), unset); +} diff --git a/crates/image-codecs/tests/it/main.rs b/crates/image-codecs/tests/it/main.rs index 380e37565..69be177db 100644 --- a/crates/image-codecs/tests/it/main.rs +++ b/crates/image-codecs/tests/it/main.rs @@ -1,5 +1,6 @@ //! The crate's integration tests, linked into one test binary. +mod bmp_resolution; mod camera_raw; mod common; mod dds;