Skip to main content

pltrs_codec/png/
metadata.rs

1//! Ancillary information carried alongside the pixels: physical resolution
2//! (`pHYs`) and text (`tEXt`, `zTXt`, `iTXt`).
3
4/// Metres per inch.
5const METRES_PER_INCH: f64 = 0.0254;
6
7/// The unit of [`PhysicalDimensions`].
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum PhysicalUnit {
10    /// Only the pixel aspect ratio is known.
11    Unknown,
12    /// Pixels per metre.
13    Meter,
14}
15
16/// Intended pixel density, from the `pHYs` chunk.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub struct PhysicalDimensions {
19    /// Pixels per unit along x.
20    pub x: u32,
21    /// Pixels per unit along y.
22    pub y: u32,
23    /// The unit `x` and `y` count pixels per.
24    pub unit: PhysicalUnit,
25}
26
27impl PhysicalDimensions {
28    /// The dimensions for `dpi` dots per inch in both directions, rounded to
29    /// whole pixels per metre the way Pillow (and hence matplotlib) does.
30    /// Returns `None` unless `dpi` is finite, positive and representable.
31    ///
32    /// ```
33    /// use pltrs_codec::png::{PhysicalDimensions, PhysicalUnit};
34    ///
35    /// let dims = PhysicalDimensions::from_dpi(100.0).unwrap();
36    /// assert_eq!((dims.x, dims.y, dims.unit), (3937, 3937, PhysicalUnit::Meter));
37    /// assert_eq!(PhysicalDimensions::from_dpi(f64::NAN), None);
38    /// ```
39    pub fn from_dpi(dpi: f64) -> Option<Self> {
40        let per_metre = (dpi / METRES_PER_INCH + 0.5).floor();
41        (dpi.is_finite() && per_metre >= 1.0 && per_metre <= f64::from(u32::MAX)).then_some(Self {
42            x: per_metre as u32,
43            y: per_metre as u32,
44            unit: PhysicalUnit::Meter,
45        })
46    }
47
48    /// Dots per inch along x and y, if the unit is known.
49    pub fn dpi(&self) -> Option<(f64, f64)> {
50        (self.unit == PhysicalUnit::Meter).then(|| {
51            (
52                f64::from(self.x) * METRES_PER_INCH,
53                f64::from(self.y) * METRES_PER_INCH,
54            )
55        })
56    }
57
58    /// The 9-byte `pHYs` payload.
59    pub(crate) fn to_bytes(self) -> [u8; 9] {
60        let mut bytes = [0; 9];
61        bytes[..4].copy_from_slice(&self.x.to_be_bytes());
62        bytes[4..8].copy_from_slice(&self.y.to_be_bytes());
63        bytes[8] = u8::from(self.unit == PhysicalUnit::Meter);
64        bytes
65    }
66
67    /// Parses a `pHYs` payload; `None` if it is malformed.
68    pub(crate) fn from_bytes(data: &[u8]) -> Option<Self> {
69        let &[x0, x1, x2, x3, y0, y1, y2, y3, unit] = <&[u8; 9]>::try_from(data).ok()?;
70        let unit = match unit {
71            0 => PhysicalUnit::Unknown,
72            1 => PhysicalUnit::Meter,
73            _ => return None,
74        };
75        Some(Self {
76            x: u32::from_be_bytes([x0, x1, x2, x3]),
77            y: u32::from_be_bytes([y0, y1, y2, y3]),
78            unit,
79        })
80    }
81}
82
83/// One textual key/value pair.
84#[derive(Clone, Debug, PartialEq, Eq, Hash)]
85pub struct TextEntry {
86    /// The keyword, e.g. `"Software"` or `"Title"`.
87    pub keyword: String,
88    /// The text.
89    pub text: String,
90}
91
92impl TextEntry {
93    /// Creates an entry.
94    pub fn new(keyword: impl Into<String>, text: impl Into<String>) -> Self {
95        Self {
96            keyword: keyword.into(),
97            text: text.into(),
98        }
99    }
100}
101
102/// Ancillary information decoded from a PNG file.
103#[derive(Clone, Debug, Default, PartialEq, Eq)]
104pub struct Metadata {
105    /// Physical pixel dimensions, from `pHYs`.
106    pub physical: Option<PhysicalDimensions>,
107    /// Text entries from `tEXt`, `zTXt` and `iTXt` chunks, in file order.
108    pub text: Vec<TextEntry>,
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn dpi_conversion_matches_pillow_rounding() {
117        let cases = [(72.0, 2835), (100.0, 3937), (150.0, 5906), (300.0, 11_811)];
118        for (dpi, per_metre) in cases {
119            let dims = PhysicalDimensions::from_dpi(dpi).unwrap();
120            assert_eq!((dims.x, dims.y), (per_metre, per_metre), "{dpi} dpi");
121            let (x, y) = dims.dpi().unwrap();
122            assert!((x - dpi).abs() < 0.02 && (y - dpi).abs() < 0.02);
123        }
124        for bad in [0.0, -5.0, f64::INFINITY, f64::NAN, 1e12, 0.001] {
125            assert_eq!(PhysicalDimensions::from_dpi(bad), None, "{bad}");
126        }
127    }
128
129    #[test]
130    fn phys_payload_round_trips() {
131        let dims = PhysicalDimensions {
132            x: 3937,
133            y: 1,
134            unit: PhysicalUnit::Meter,
135        };
136        let bytes = dims.to_bytes();
137        assert_eq!(bytes, [0, 0, 0x0F, 0x61, 0, 0, 0, 1, 1]);
138        assert_eq!(PhysicalDimensions::from_bytes(&bytes), Some(dims));
139        assert_eq!(PhysicalDimensions::from_bytes(&bytes[..8]), None);
140        let mut bad_unit = bytes;
141        bad_unit[8] = 2;
142        assert_eq!(PhysicalDimensions::from_bytes(&bad_unit), None);
143        let aspect = PhysicalDimensions {
144            unit: PhysicalUnit::Unknown,
145            ..dims
146        };
147        assert_eq!(aspect.dpi(), None);
148    }
149}