rustypyxl 0.7.1

Fast, dependency-light Rust library for reading and writing Excel (XLSX) files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Image support for Excel workbooks.
//!
//! This module provides structures for inserting and managing images in Excel files.
//!
//! **Status: write path + round-trip.** An [`Image`] added to a worksheet is embedded on
//! save (media part, drawing anchor, and relationships), and images already present in a
//! loaded file are preserved when it is saved again. PNG, JPEG, GIF, BMP, and TIFF are
//! detected from magic bytes or extension. Charts and images on one sheet share a single
//! drawing part.

use std::path::PathBuf;

/// Supported image formats.
#[derive(Clone, Debug, PartialEq)]
pub enum ImageFormat {
    /// PNG image.
    Png,
    /// JPEG image.
    Jpeg,
    /// GIF image.
    Gif,
    /// Windows Enhanced Metafile.
    Emf,
    /// Windows Metafile.
    Wmf,
    /// BMP image.
    Bmp,
    /// TIFF image.
    Tiff,
}

impl ImageFormat {
    /// Get the file extension for this format.
    pub fn extension(&self) -> &'static str {
        match self {
            ImageFormat::Png => "png",
            ImageFormat::Jpeg => "jpeg",
            ImageFormat::Gif => "gif",
            ImageFormat::Emf => "emf",
            ImageFormat::Wmf => "wmf",
            ImageFormat::Bmp => "bmp",
            ImageFormat::Tiff => "tiff",
        }
    }

    /// Get the content type for this format.
    pub fn content_type(&self) -> &'static str {
        match self {
            ImageFormat::Png => "image/png",
            ImageFormat::Jpeg => "image/jpeg",
            ImageFormat::Gif => "image/gif",
            ImageFormat::Emf => "image/x-emf",
            ImageFormat::Wmf => "image/x-wmf",
            ImageFormat::Bmp => "image/bmp",
            ImageFormat::Tiff => "image/tiff",
        }
    }

    /// Detect format from file extension.
    pub fn from_extension(ext: &str) -> Option<Self> {
        match ext.to_lowercase().as_str() {
            "png" => Some(ImageFormat::Png),
            "jpg" | "jpeg" => Some(ImageFormat::Jpeg),
            "gif" => Some(ImageFormat::Gif),
            "emf" => Some(ImageFormat::Emf),
            "wmf" => Some(ImageFormat::Wmf),
            "bmp" => Some(ImageFormat::Bmp),
            "tif" | "tiff" => Some(ImageFormat::Tiff),
            _ => None,
        }
    }

    /// Detect format from magic bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() < 8 {
            return None;
        }

        // PNG: 89 50 4E 47 0D 0A 1A 0A
        if data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
            return Some(ImageFormat::Png);
        }

        // JPEG: FF D8 FF
        if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
            return Some(ImageFormat::Jpeg);
        }

        // GIF: GIF87a or GIF89a
        if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
            return Some(ImageFormat::Gif);
        }

        // BMP: BM
        if data.starts_with(b"BM") {
            return Some(ImageFormat::Bmp);
        }

        // TIFF: II or MM
        if data.starts_with(&[0x49, 0x49, 0x2A, 0x00])
            || data.starts_with(&[0x4D, 0x4D, 0x00, 0x2A])
        {
            return Some(ImageFormat::Tiff);
        }

        None
    }
}

/// Anchor type for positioning images.
#[derive(Clone, Debug, PartialEq)]
pub enum ImageAnchorType {
    /// One cell anchor - image moves with cell but doesn't resize.
    OneCell,
    /// Two cell anchor - image moves and resizes with cells.
    TwoCell,
    /// Absolute anchor - fixed position.
    Absolute,
}

/// Position anchor for an image.
#[derive(Clone, Debug)]
pub struct ImageAnchor {
    /// Anchor type.
    pub anchor_type: ImageAnchorType,
    /// Starting cell (e.g., "A1").
    pub from_cell: String,
    /// Column offset from cell in EMUs.
    pub from_col_offset: u32,
    /// Row offset from cell in EMUs.
    pub from_row_offset: u32,
    /// Ending cell for two-cell anchors.
    pub to_cell: Option<String>,
    /// Column offset for ending cell.
    pub to_col_offset: u32,
    /// Row offset for ending cell.
    pub to_row_offset: u32,
}

impl ImageAnchor {
    /// Create a one-cell anchor at the specified cell.
    pub fn one_cell<S: Into<String>>(cell: S) -> Self {
        ImageAnchor {
            anchor_type: ImageAnchorType::OneCell,
            from_cell: cell.into(),
            from_col_offset: 0,
            from_row_offset: 0,
            to_cell: None,
            to_col_offset: 0,
            to_row_offset: 0,
        }
    }

    /// Create a two-cell anchor spanning from one cell to another.
    pub fn two_cell<S1: Into<String>, S2: Into<String>>(from: S1, to: S2) -> Self {
        ImageAnchor {
            anchor_type: ImageAnchorType::TwoCell,
            from_cell: from.into(),
            from_col_offset: 0,
            from_row_offset: 0,
            to_cell: Some(to.into()),
            to_col_offset: 0,
            to_row_offset: 0,
        }
    }

    /// Set offsets in pixels (converted to EMUs).
    pub fn with_offset_px(mut self, col_px: u32, row_px: u32) -> Self {
        // Approximately 9525 EMUs per pixel
        self.from_col_offset = col_px * 9525;
        self.from_row_offset = row_px * 9525;
        self
    }
}

/// An image in an Excel worksheet.
#[derive(Clone, Debug)]
pub struct Image {
    /// Image data (bytes).
    pub data: Vec<u8>,
    /// Image format.
    pub format: ImageFormat,
    /// Original file path (if loaded from file).
    pub source_path: Option<PathBuf>,
    /// Position anchor.
    pub anchor: ImageAnchor,
    /// Width in EMUs (914400 EMUs = 1 inch).
    pub width: u32,
    /// Height in EMUs.
    pub height: u32,
    /// Alternative text for accessibility.
    pub alt_text: Option<String>,
    /// Description.
    pub description: Option<String>,
    /// Name/title.
    pub name: Option<String>,
}

impl Image {
    /// Create a new image from bytes.
    pub fn from_bytes(data: Vec<u8>, anchor: ImageAnchor) -> Option<Self> {
        let format = ImageFormat::from_bytes(&data)?;
        Some(Image {
            data,
            format,
            source_path: None,
            anchor,
            width: 914400,  // 1 inch default
            height: 914400, // 1 inch default
            alt_text: None,
            description: None,
            name: None,
        })
    }

    /// Create a new image from a file path.
    pub fn from_file(path: &std::path::Path, anchor: ImageAnchor) -> std::io::Result<Self> {
        let data = std::fs::read(path)?;

        let format = path
            .extension()
            .and_then(|e| e.to_str())
            .and_then(ImageFormat::from_extension)
            .or_else(|| ImageFormat::from_bytes(&data))
            .ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::InvalidData, "Unknown image format")
            })?;

        Ok(Image {
            data,
            format,
            source_path: Some(path.to_path_buf()),
            anchor,
            width: 914400,
            height: 914400,
            alt_text: None,
            description: None,
            name: None,
        })
    }

    /// Set the image size in inches.
    pub fn with_size_inches(mut self, width: f64, height: f64) -> Self {
        self.width = (width * 914400.0) as u32;
        self.height = (height * 914400.0) as u32;
        self
    }

    /// Set the image size in pixels (at 96 DPI).
    pub fn with_size_px(mut self, width: u32, height: u32) -> Self {
        // 9525 EMUs per pixel at 96 DPI
        self.width = width * 9525;
        self.height = height * 9525;
        self
    }

    /// Set alternative text.
    pub fn with_alt_text<S: Into<String>>(mut self, text: S) -> Self {
        self.alt_text = Some(text.into());
        self
    }

    /// Set the image name.
    pub fn with_name<S: Into<String>>(mut self, name: S) -> Self {
        self.name = Some(name.into());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_image_format_detection() {
        // PNG magic bytes
        let png_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
        assert_eq!(ImageFormat::from_bytes(&png_data), Some(ImageFormat::Png));

        // JPEG magic bytes (need at least 8 bytes for detection)
        let jpeg_data = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46];
        assert_eq!(ImageFormat::from_bytes(&jpeg_data), Some(ImageFormat::Jpeg));

        // GIF magic bytes (need at least 8 bytes for detection)
        let gif_data = b"GIF89a\x00\x00".to_vec();
        assert_eq!(ImageFormat::from_bytes(&gif_data), Some(ImageFormat::Gif));
    }

    #[test]
    fn test_format_from_extension() {
        assert_eq!(ImageFormat::from_extension("png"), Some(ImageFormat::Png));
        assert_eq!(ImageFormat::from_extension("PNG"), Some(ImageFormat::Png));
        assert_eq!(ImageFormat::from_extension("jpg"), Some(ImageFormat::Jpeg));
        assert_eq!(ImageFormat::from_extension("jpeg"), Some(ImageFormat::Jpeg));
    }

    #[test]
    fn test_image_anchor() {
        let anchor = ImageAnchor::one_cell("A1");
        assert_eq!(anchor.anchor_type, ImageAnchorType::OneCell);
        assert_eq!(anchor.from_cell, "A1");

        let anchor = ImageAnchor::two_cell("A1", "C5");
        assert_eq!(anchor.anchor_type, ImageAnchorType::TwoCell);
        assert_eq!(anchor.to_cell, Some("C5".to_string()));
    }

    #[test]
    fn test_image_size() {
        let png_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
        let image = Image::from_bytes(png_data, ImageAnchor::one_cell("A1"))
            .unwrap()
            .with_size_inches(2.0, 1.5);

        assert_eq!(image.width, 1828800); // 2 * 914400
        assert_eq!(image.height, 1371600); // 1.5 * 914400
    }

    #[test]
    fn test_content_type() {
        assert_eq!(ImageFormat::Png.content_type(), "image/png");
        assert_eq!(ImageFormat::Jpeg.content_type(), "image/jpeg");
    }
}

#[cfg(test)]
mod coverage_tests {
    use super::*;

    #[test]
    fn format_extensions_and_content_types() {
        for (fmt, ext, ct) in [
            (ImageFormat::Png, "png", "image/png"),
            (ImageFormat::Jpeg, "jpeg", "image/jpeg"),
            (ImageFormat::Gif, "gif", "image/gif"),
            (ImageFormat::Bmp, "bmp", "image/bmp"),
            (ImageFormat::Tiff, "tiff", "image/tiff"),
            (ImageFormat::Emf, "emf", "image/x-emf"),
            (ImageFormat::Wmf, "wmf", "image/x-wmf"),
        ] {
            assert_eq!(fmt.extension(), ext);
            assert_eq!(fmt.content_type(), ct);
        }
    }

    #[test]
    fn format_from_extension_variants() {
        assert_eq!(ImageFormat::from_extension("JPG"), Some(ImageFormat::Jpeg));
        assert_eq!(ImageFormat::from_extension("tif"), Some(ImageFormat::Tiff));
        assert_eq!(ImageFormat::from_extension("PNG"), Some(ImageFormat::Png));
        assert_eq!(ImageFormat::from_extension("webp"), None);
    }

    #[test]
    fn format_from_magic_bytes() {
        assert_eq!(
            ImageFormat::from_bytes(&[0x42, 0x4D, 0, 0, 0, 0, 0, 0]),
            Some(ImageFormat::Bmp)
        );
        assert_eq!(
            ImageFormat::from_bytes(&[0x49, 0x49, 0x2A, 0x00, 0, 0, 0, 0]),
            Some(ImageFormat::Tiff)
        );
        assert_eq!(
            ImageFormat::from_bytes(&[0x4D, 0x4D, 0x00, 0x2A, 0, 0, 0, 0]),
            Some(ImageFormat::Tiff)
        );
        assert_eq!(ImageFormat::from_bytes(&[0, 1, 2]), None); // too short
        assert_eq!(ImageFormat::from_bytes(&[0; 8]), None); // unknown
    }

    #[test]
    fn anchor_builders() {
        let one = ImageAnchor::one_cell("B2").with_offset_px(10, 20);
        assert_eq!(one.anchor_type, ImageAnchorType::OneCell);
        assert_eq!(one.from_cell, "B2");
        assert_eq!(one.from_col_offset, 10 * 9525);
        assert_eq!(one.from_row_offset, 20 * 9525);

        let two = ImageAnchor::two_cell("A1", "D4");
        assert_eq!(two.anchor_type, ImageAnchorType::TwoCell);
        assert_eq!(two.to_cell.as_deref(), Some("D4"));
    }

    #[test]
    fn image_builders_and_sizing() {
        let png = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
        let img = Image::from_bytes(png, ImageAnchor::one_cell("A1"))
            .unwrap()
            .with_size_inches(2.0, 1.0)
            .with_alt_text("alt")
            .with_name("logo");
        assert_eq!(img.format, ImageFormat::Png);
        assert_eq!(img.width, 1828800);
        assert_eq!(img.height, 914400);
        assert_eq!(img.alt_text.as_deref(), Some("alt"));
        assert_eq!(img.name.as_deref(), Some("logo"));

        // Unrecognized bytes yield no image.
        assert!(
            Image::from_bytes(vec![0, 1, 2, 3, 4, 5, 6, 7], ImageAnchor::one_cell("A1")).is_none()
        );
    }

    #[test]
    fn image_from_file_reads_and_detects() {
        let dir = std::env::temp_dir();
        let path = dir.join("rustypyxl_cov_test.png");
        std::fs::write(&path, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]).unwrap();
        let img = Image::from_file(&path, ImageAnchor::one_cell("A1")).unwrap();
        assert_eq!(img.format, ImageFormat::Png);
        assert!(img.source_path.is_some());
        let _ = std::fs::remove_file(&path);
    }
}