Skip to main content

f_office/edit/
image.rs

1//! The image file of an image edit ([`NamedEdit::InsertImage`](super::NamedEdit)): its format
2//! by its first bytes, never by its name, and its size at its own resolution by its header.
3
4use std::fmt;
5
6use f_office_docx::named_edits::ImageFile;
7use f_office_paint::ImageFormat;
8use f_office_units::scale::{EMUS_PER_INCH, TENTHS_OF_MM_PER_CM, TENTHS_OF_MM_PER_INCH};
9use f_office_units::{Length, div_round_i128};
10
11use super::EditLimits;
12use f_office_paint::image_header::{DensityUnit, ImageHeader, jpeg_header, png_header};
13
14/// The resolution of an image whose file gives none, in pixels per inch: the resolution of a
15/// screen at a scale of 100 % in Windows, at which CSS also takes a pixel to be 1/96 inch.
16const PIXELS_PER_INCH: u32 = 96;
17
18/// One meter in tenths of a millimeter.
19const TENTHS_OF_MM_PER_METER: i64 = 10_000;
20
21/// Why a file is not an image that an edit inserts. Each message names the fix.
22#[derive(Clone, Debug, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum ImageError {
25    /// The file is larger than [`EditLimits::max_image_bytes`].
26    TooLarge {
27        /// The limit.
28        limit: usize,
29    },
30    /// The file is of a format other than PNG and JPEG, by its first bytes.
31    Format(ImageFormat),
32    /// The file's header does not read.
33    Header,
34    /// The image has no pixels, or a size at its resolution that is too large for a file.
35    Size,
36}
37
38impl fmt::Display for ImageError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::TooLarge { limit } => write!(
42                f,
43                "the image file is larger than {limit} bytes: save it smaller"
44            ),
45            Self::Format(ImageFormat::Unknown) => f.write_str(
46                "the image file is of no known format by its first bytes, and an image edit takes only PNG and JPEG files: convert it to PNG",
47            ),
48            Self::Format(format) => write!(
49                f,
50                "the image file is a {format} file by its first bytes, and an image edit takes only PNG and JPEG files: convert it to PNG"
51            ),
52            Self::Header => {
53                f.write_str("the image file's header does not read: save the image again")
54            }
55            Self::Size => f.write_str(
56                "the image has no pixels, or a size at its resolution that is too large for a file: save it with another size or resolution",
57            ),
58        }
59    }
60}
61
62impl std::error::Error for ImageError {}
63
64/// The image file `data` of an image edit: a PNG or a JPEG file by its first bytes, with its
65/// size at the resolution that its header gives, or at 96 pixels per inch when it gives none.
66///
67/// # Errors
68///
69/// Returns [`ImageError`] for a file beyond `limits`, of another format, whose header does not
70/// read, or without a size.
71pub fn image_file(data: Vec<u8>, limits: &EditLimits) -> Result<ImageFile, ImageError> {
72    if data.len() > limits.max_image_bytes {
73        return Err(ImageError::TooLarge {
74            limit: limits.max_image_bytes,
75        });
76    }
77    let format = ImageFormat::detect(&data);
78    let header = match format {
79        ImageFormat::Png => png_header(&data),
80        ImageFormat::Jpeg => jpeg_header(&data),
81        other => return Err(ImageError::Format(other)),
82    }
83    .ok_or(ImageError::Header)?;
84    let size = own_size(&header).ok_or(ImageError::Size)?;
85    ImageFile::new(format, data, size).ok_or(ImageError::Size)
86}
87
88/// The width and the height of the image of `header` at its resolution.
89fn own_size(header: &ImageHeader) -> Option<(Length, Length)> {
90    let (per_x, per_y, unit) =
91        header
92            .density
93            .unwrap_or((PIXELS_PER_INCH, PIXELS_PER_INCH, DensityUnit::Inch));
94    let unit = i128::from(match unit {
95        DensityUnit::Inch => TENTHS_OF_MM_PER_INCH,
96        DensityUnit::Centimeter => TENTHS_OF_MM_PER_CM,
97        DensityUnit::Meter => TENTHS_OF_MM_PER_METER,
98    });
99    let length = |pixels: usize, per_unit: u32| {
100        let emus = div_round_i128(
101            i128::try_from(pixels).ok()? * i128::from(EMUS_PER_INCH) * unit,
102            i128::from(TENTHS_OF_MM_PER_INCH) * i128::from(per_unit),
103        );
104        Length::from_emus(i64::try_from(emus).ok()?)
105    };
106    Some((
107        length(header.pixels.0, per_x)?,
108        length(header.pixels.1, per_y)?,
109    ))
110}
111
112#[cfg(test)]
113mod tests {
114    use f_office_paint::ImageFormat;
115    use f_office_units::Length;
116
117    use super::{EditLimits, ImageError, image_file};
118
119    /// A PNG file of `width` by `height` pixels with the chunk `phys` after its header, if
120    /// given, each chunk with a CRC of zeros, which the reader does not check.
121    fn png(width: u32, height: u32, phys: Option<(u32, u32)>) -> Vec<u8> {
122        let mut file = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
123        file.extend_from_slice(&width.to_be_bytes());
124        file.extend_from_slice(&height.to_be_bytes());
125        file.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
126        if let Some((x, y)) = phys {
127            file.extend_from_slice(b"\0\0\0\x09pHYs");
128            file.extend_from_slice(&x.to_be_bytes());
129            file.extend_from_slice(&y.to_be_bytes());
130            file.extend_from_slice(&[1, 0, 0, 0, 0]);
131        }
132        file.extend_from_slice(b"\0\0\0\0IEND\0\0\0\0");
133        file
134    }
135
136    fn inches(thousandths: i64) -> Length {
137        Length::from_emus(914_400 * thousandths / 1_000).unwrap()
138    }
139
140    #[test]
141    fn a_file_without_a_resolution_takes_96_pixels_per_inch() {
142        let image = image_file(png(192, 96, None), &EditLimits::default()).unwrap();
143        assert_eq!(image.format(), ImageFormat::Png);
144        assert_eq!(image.size(), (inches(2_000), inches(1_000)));
145    }
146
147    #[test]
148    fn a_file_takes_its_own_resolution() {
149        // 11,811 pixels per meter are 300 pixels per inch, to the nearest whole one.
150        let image = image_file(
151            png(300, 600, Some((11_811, 11_811))),
152            &EditLimits::default(),
153        )
154        .unwrap();
155        let (width, height) = image.size();
156        assert!((width.units() - inches(1_000).units()).abs() <= 100);
157        assert!((height.units() - inches(2_000).units()).abs() <= 100);
158    }
159
160    #[test]
161    fn the_format_comes_from_the_first_bytes() {
162        let limits = EditLimits::default();
163        assert_eq!(
164            image_file(b"GIF89a....".to_vec(), &limits),
165            Err(ImageError::Format(ImageFormat::Gif))
166        );
167        assert_eq!(
168            image_file(b"not an image".to_vec(), &limits),
169            Err(ImageError::Format(ImageFormat::Unknown))
170        );
171        assert_eq!(
172            image_file(b"\x89PNG\r\n\x1a\n cut".to_vec(), &limits),
173            Err(ImageError::Header)
174        );
175        assert_eq!(image_file(png(0, 10, None), &limits), Err(ImageError::Size));
176    }
177
178    #[test]
179    fn a_file_beyond_the_limit_is_refused() {
180        let limits = EditLimits {
181            max_image_bytes: 10,
182            ..EditLimits::default()
183        };
184        assert_eq!(
185            image_file(png(1, 1, None), &limits),
186            Err(ImageError::TooLarge { limit: 10 })
187        );
188    }
189}