Skip to main content

sheetkit_core/
image.rs

1//! Image insertion and management.
2//!
3//! Provides types for configuring image placement in worksheets and
4//! helpers for building the corresponding drawing XML structures.
5
6use sheetkit_xml::drawing::{
7    AExt, Blip, BlipFill, CNvPicPr, CNvPr, ClientData, Extent, FillRect, MarkerType, NvPicPr,
8    Offset, OneCellAnchor, Picture, PrstGeom, SpPr, Stretch, WsDr, Xfrm,
9};
10
11use crate::error::{Error, Result};
12use crate::utils::cell_ref::cell_name_to_coordinates;
13
14/// EMU (English Metric Units) per pixel at 96 DPI.
15/// 1 inch = 914400 EMU, 1 inch = 96 pixels => 1 pixel = 9525 EMU.
16pub const EMU_PER_PIXEL: u64 = 9525;
17
18/// Supported image formats.
19#[derive(Debug, Clone, PartialEq)]
20pub enum ImageFormat {
21    /// PNG image.
22    Png,
23    /// JPEG image.
24    Jpeg,
25    /// GIF image.
26    Gif,
27    /// BMP image.
28    Bmp,
29    /// ICO image.
30    Ico,
31    /// TIFF image.
32    Tiff,
33    /// SVG image.
34    Svg,
35    /// EMF (Enhanced Metafile) image.
36    Emf,
37    /// EMZ (compressed EMF) image.
38    Emz,
39    /// WMF (Windows Metafile) image.
40    Wmf,
41    /// WMZ (compressed WMF) image.
42    Wmz,
43}
44
45impl ImageFormat {
46    /// Parse an extension string into an `ImageFormat`.
47    ///
48    /// Accepts common aliases such as `"jpg"` for JPEG and `"tif"` for TIFF.
49    /// Returns `Error::UnsupportedImageFormat` for unrecognised strings.
50    pub fn from_extension(ext: &str) -> Result<Self> {
51        match ext.to_ascii_lowercase().as_str() {
52            "png" => Ok(ImageFormat::Png),
53            "jpeg" | "jpg" => Ok(ImageFormat::Jpeg),
54            "gif" => Ok(ImageFormat::Gif),
55            "bmp" => Ok(ImageFormat::Bmp),
56            "ico" => Ok(ImageFormat::Ico),
57            "tiff" | "tif" => Ok(ImageFormat::Tiff),
58            "svg" => Ok(ImageFormat::Svg),
59            "emf" => Ok(ImageFormat::Emf),
60            "emz" => Ok(ImageFormat::Emz),
61            "wmf" => Ok(ImageFormat::Wmf),
62            "wmz" => Ok(ImageFormat::Wmz),
63            _ => Err(Error::UnsupportedImageFormat {
64                format: ext.to_string(),
65            }),
66        }
67    }
68
69    /// Return the MIME content type string for this image format.
70    pub fn content_type(&self) -> &str {
71        match self {
72            ImageFormat::Png => "image/png",
73            ImageFormat::Jpeg => "image/jpeg",
74            ImageFormat::Gif => "image/gif",
75            ImageFormat::Bmp => "image/bmp",
76            ImageFormat::Ico => "image/x-icon",
77            ImageFormat::Tiff => "image/tiff",
78            ImageFormat::Svg => "image/svg+xml",
79            ImageFormat::Emf => "image/x-emf",
80            ImageFormat::Emz => "image/x-emz",
81            ImageFormat::Wmf => "image/x-wmf",
82            ImageFormat::Wmz => "image/x-wmz",
83        }
84    }
85
86    /// Return the file extension for this image format.
87    pub fn extension(&self) -> &str {
88        match self {
89            ImageFormat::Png => "png",
90            ImageFormat::Jpeg => "jpeg",
91            ImageFormat::Gif => "gif",
92            ImageFormat::Bmp => "bmp",
93            ImageFormat::Ico => "ico",
94            ImageFormat::Tiff => "tiff",
95            ImageFormat::Svg => "svg",
96            ImageFormat::Emf => "emf",
97            ImageFormat::Emz => "emz",
98            ImageFormat::Wmf => "wmf",
99            ImageFormat::Wmz => "wmz",
100        }
101    }
102}
103
104/// Information about a picture retrieved from a worksheet.
105#[derive(Debug, Clone)]
106pub struct PictureInfo {
107    /// Raw image bytes.
108    pub data: Vec<u8>,
109    /// Image format.
110    pub format: ImageFormat,
111    /// Anchor cell reference (e.g., `"B2"`).
112    pub cell: String,
113    /// Image width in pixels.
114    pub width_px: u32,
115    /// Image height in pixels.
116    pub height_px: u32,
117}
118
119/// Configuration for inserting an image into a worksheet.
120#[derive(Debug, Clone)]
121pub struct ImageConfig {
122    /// Raw image bytes.
123    pub data: Vec<u8>,
124    /// Image format.
125    pub format: ImageFormat,
126    /// Anchor cell reference (e.g., `"B2"`).
127    pub from_cell: String,
128    /// Image width in pixels.
129    pub width_px: u32,
130    /// Image height in pixels.
131    pub height_px: u32,
132}
133
134/// Convert pixel dimensions to EMU.
135pub fn pixels_to_emu(px: u32) -> u64 {
136    px as u64 * EMU_PER_PIXEL
137}
138
139/// Build a drawing XML structure containing a single image.
140///
141/// The image is anchored to a single cell (one-cell anchor) with explicit
142/// width and height in EMU derived from pixel dimensions.
143pub fn build_drawing_with_image(image_ref_id: &str, config: &ImageConfig) -> Result<WsDr> {
144    let (col, row) = cell_name_to_coordinates(&config.from_cell)?;
145    // MarkerType uses 0-based column and row indices
146    let from = MarkerType {
147        col: col - 1,
148        col_off: 0,
149        row: row - 1,
150        row_off: 0,
151    };
152
153    let cx = pixels_to_emu(config.width_px);
154    let cy = pixels_to_emu(config.height_px);
155
156    let pic = Picture {
157        nv_pic_pr: NvPicPr {
158            c_nv_pr: CNvPr {
159                id: 2,
160                name: "Picture 1".to_string(),
161            },
162            c_nv_pic_pr: CNvPicPr {},
163        },
164        blip_fill: BlipFill {
165            blip: Blip {
166                r_embed: image_ref_id.to_string(),
167            },
168            stretch: Stretch {
169                fill_rect: FillRect {},
170            },
171        },
172        sp_pr: SpPr {
173            xfrm: Xfrm {
174                off: Offset { x: 0, y: 0 },
175                ext: AExt { cx, cy },
176            },
177            prst_geom: PrstGeom {
178                prst: "rect".to_string(),
179            },
180        },
181    };
182
183    let anchor = OneCellAnchor {
184        from,
185        ext: Extent { cx, cy },
186        pic: Some(pic),
187        alternate_content: None,
188        client_data: ClientData {},
189    };
190
191    Ok(WsDr {
192        one_cell_anchors: vec![anchor],
193        ..WsDr::default()
194    })
195}
196
197/// Add an image anchor to an existing drawing.
198///
199/// If a drawing already exists for a sheet (e.g., it already has a chart),
200/// this function adds the image anchor to it.
201pub fn add_image_to_drawing(
202    drawing: &mut WsDr,
203    image_ref_id: &str,
204    config: &ImageConfig,
205    pic_id: u32,
206) -> Result<()> {
207    let (col, row) = cell_name_to_coordinates(&config.from_cell)?;
208    let from = MarkerType {
209        col: col - 1,
210        col_off: 0,
211        row: row - 1,
212        row_off: 0,
213    };
214
215    let cx = pixels_to_emu(config.width_px);
216    let cy = pixels_to_emu(config.height_px);
217
218    let pic = Picture {
219        nv_pic_pr: NvPicPr {
220            c_nv_pr: CNvPr {
221                id: pic_id,
222                name: format!("Picture {}", pic_id - 1),
223            },
224            c_nv_pic_pr: CNvPicPr {},
225        },
226        blip_fill: BlipFill {
227            blip: Blip {
228                r_embed: image_ref_id.to_string(),
229            },
230            stretch: Stretch {
231                fill_rect: FillRect {},
232            },
233        },
234        sp_pr: SpPr {
235            xfrm: Xfrm {
236                off: Offset { x: 0, y: 0 },
237                ext: AExt { cx, cy },
238            },
239            prst_geom: PrstGeom {
240                prst: "rect".to_string(),
241            },
242        },
243    };
244
245    drawing.one_cell_anchors.push(OneCellAnchor {
246        from,
247        ext: Extent { cx, cy },
248        pic: Some(pic),
249        alternate_content: None,
250        client_data: ClientData {},
251    });
252
253    Ok(())
254}
255
256/// Validate an ImageConfig.
257pub fn validate_image_config(config: &ImageConfig) -> Result<()> {
258    if config.data.is_empty() {
259        return Err(Error::Internal("image data is empty".to_string()));
260    }
261    if config.width_px == 0 || config.height_px == 0 {
262        return Err(Error::Internal(
263            "image dimensions must be non-zero".to_string(),
264        ));
265    }
266    // Validate the cell reference
267    cell_name_to_coordinates(&config.from_cell)?;
268    Ok(())
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn test_emu_per_pixel_constant() {
277        assert_eq!(EMU_PER_PIXEL, 9525);
278    }
279
280    #[test]
281    fn test_pixels_to_emu() {
282        assert_eq!(pixels_to_emu(1), 9525);
283        assert_eq!(pixels_to_emu(100), 952500);
284        assert_eq!(pixels_to_emu(1000), 9525000);
285        assert_eq!(pixels_to_emu(0), 0);
286    }
287
288    #[test]
289    fn test_image_format_content_type_original() {
290        assert_eq!(ImageFormat::Png.content_type(), "image/png");
291        assert_eq!(ImageFormat::Jpeg.content_type(), "image/jpeg");
292        assert_eq!(ImageFormat::Gif.content_type(), "image/gif");
293    }
294
295    #[test]
296    fn test_image_format_content_type_new_formats() {
297        assert_eq!(ImageFormat::Bmp.content_type(), "image/bmp");
298        assert_eq!(ImageFormat::Ico.content_type(), "image/x-icon");
299        assert_eq!(ImageFormat::Tiff.content_type(), "image/tiff");
300        assert_eq!(ImageFormat::Svg.content_type(), "image/svg+xml");
301        assert_eq!(ImageFormat::Emf.content_type(), "image/x-emf");
302        assert_eq!(ImageFormat::Emz.content_type(), "image/x-emz");
303        assert_eq!(ImageFormat::Wmf.content_type(), "image/x-wmf");
304        assert_eq!(ImageFormat::Wmz.content_type(), "image/x-wmz");
305    }
306
307    #[test]
308    fn test_image_format_extension_original() {
309        assert_eq!(ImageFormat::Png.extension(), "png");
310        assert_eq!(ImageFormat::Jpeg.extension(), "jpeg");
311        assert_eq!(ImageFormat::Gif.extension(), "gif");
312    }
313
314    #[test]
315    fn test_image_format_extension_new_formats() {
316        assert_eq!(ImageFormat::Bmp.extension(), "bmp");
317        assert_eq!(ImageFormat::Ico.extension(), "ico");
318        assert_eq!(ImageFormat::Tiff.extension(), "tiff");
319        assert_eq!(ImageFormat::Svg.extension(), "svg");
320        assert_eq!(ImageFormat::Emf.extension(), "emf");
321        assert_eq!(ImageFormat::Emz.extension(), "emz");
322        assert_eq!(ImageFormat::Wmf.extension(), "wmf");
323        assert_eq!(ImageFormat::Wmz.extension(), "wmz");
324    }
325
326    #[test]
327    fn test_from_extension_original_formats() {
328        assert_eq!(
329            ImageFormat::from_extension("png").unwrap(),
330            ImageFormat::Png
331        );
332        assert_eq!(
333            ImageFormat::from_extension("jpeg").unwrap(),
334            ImageFormat::Jpeg
335        );
336        assert_eq!(
337            ImageFormat::from_extension("jpg").unwrap(),
338            ImageFormat::Jpeg
339        );
340        assert_eq!(
341            ImageFormat::from_extension("gif").unwrap(),
342            ImageFormat::Gif
343        );
344    }
345
346    #[test]
347    fn test_from_extension_new_formats() {
348        assert_eq!(
349            ImageFormat::from_extension("bmp").unwrap(),
350            ImageFormat::Bmp
351        );
352        assert_eq!(
353            ImageFormat::from_extension("ico").unwrap(),
354            ImageFormat::Ico
355        );
356        assert_eq!(
357            ImageFormat::from_extension("tiff").unwrap(),
358            ImageFormat::Tiff
359        );
360        assert_eq!(
361            ImageFormat::from_extension("tif").unwrap(),
362            ImageFormat::Tiff
363        );
364        assert_eq!(
365            ImageFormat::from_extension("svg").unwrap(),
366            ImageFormat::Svg
367        );
368        assert_eq!(
369            ImageFormat::from_extension("emf").unwrap(),
370            ImageFormat::Emf
371        );
372        assert_eq!(
373            ImageFormat::from_extension("emz").unwrap(),
374            ImageFormat::Emz
375        );
376        assert_eq!(
377            ImageFormat::from_extension("wmf").unwrap(),
378            ImageFormat::Wmf
379        );
380        assert_eq!(
381            ImageFormat::from_extension("wmz").unwrap(),
382            ImageFormat::Wmz
383        );
384    }
385
386    #[test]
387    fn test_from_extension_case_insensitive() {
388        assert_eq!(
389            ImageFormat::from_extension("PNG").unwrap(),
390            ImageFormat::Png
391        );
392        assert_eq!(
393            ImageFormat::from_extension("Jpeg").unwrap(),
394            ImageFormat::Jpeg
395        );
396        assert_eq!(
397            ImageFormat::from_extension("TIFF").unwrap(),
398            ImageFormat::Tiff
399        );
400        assert_eq!(
401            ImageFormat::from_extension("SVG").unwrap(),
402            ImageFormat::Svg
403        );
404        assert_eq!(
405            ImageFormat::from_extension("Emf").unwrap(),
406            ImageFormat::Emf
407        );
408    }
409
410    #[test]
411    fn test_from_extension_unknown_returns_error() {
412        let result = ImageFormat::from_extension("webp");
413        assert!(result.is_err());
414        let err = result.unwrap_err();
415        assert!(matches!(err, Error::UnsupportedImageFormat { .. }));
416        assert!(err.to_string().contains("webp"));
417    }
418
419    #[test]
420    fn test_from_extension_empty_returns_error() {
421        let result = ImageFormat::from_extension("");
422        assert!(result.is_err());
423        assert!(matches!(
424            result.unwrap_err(),
425            Error::UnsupportedImageFormat { .. }
426        ));
427    }
428
429    #[test]
430    fn test_from_extension_roundtrip() {
431        let formats = [
432            ImageFormat::Png,
433            ImageFormat::Jpeg,
434            ImageFormat::Gif,
435            ImageFormat::Bmp,
436            ImageFormat::Ico,
437            ImageFormat::Tiff,
438            ImageFormat::Svg,
439            ImageFormat::Emf,
440            ImageFormat::Emz,
441            ImageFormat::Wmf,
442            ImageFormat::Wmz,
443        ];
444        for fmt in &formats {
445            let ext = fmt.extension();
446            let parsed = ImageFormat::from_extension(ext).unwrap();
447            assert_eq!(&parsed, fmt);
448        }
449    }
450
451    #[test]
452    fn test_build_drawing_with_image() {
453        let config = ImageConfig {
454            data: vec![0x89, 0x50, 0x4E, 0x47],
455            format: ImageFormat::Png,
456            from_cell: "B2".to_string(),
457            width_px: 400,
458            height_px: 300,
459        };
460
461        let dr = build_drawing_with_image("rId1", &config).unwrap();
462
463        assert!(dr.two_cell_anchors.is_empty());
464        assert_eq!(dr.one_cell_anchors.len(), 1);
465
466        let anchor = &dr.one_cell_anchors[0];
467        assert_eq!(anchor.from.col, 1);
468        assert_eq!(anchor.from.row, 1);
469        assert_eq!(anchor.ext.cx, 400 * 9525);
470        assert_eq!(anchor.ext.cy, 300 * 9525);
471
472        let pic = anchor.pic.as_ref().unwrap();
473        assert_eq!(pic.blip_fill.blip.r_embed, "rId1");
474        assert_eq!(pic.sp_pr.prst_geom.prst, "rect");
475    }
476
477    #[test]
478    fn test_build_drawing_with_image_a1() {
479        let config = ImageConfig {
480            data: vec![0xFF, 0xD8],
481            format: ImageFormat::Jpeg,
482            from_cell: "A1".to_string(),
483            width_px: 200,
484            height_px: 100,
485        };
486
487        let dr = build_drawing_with_image("rId2", &config).unwrap();
488        let anchor = &dr.one_cell_anchors[0];
489        assert_eq!(anchor.from.col, 0);
490        assert_eq!(anchor.from.row, 0);
491    }
492
493    #[test]
494    fn test_build_drawing_with_image_invalid_cell() {
495        let config = ImageConfig {
496            data: vec![0x89],
497            format: ImageFormat::Png,
498            from_cell: "INVALID".to_string(),
499            width_px: 100,
500            height_px: 100,
501        };
502
503        let result = build_drawing_with_image("rId1", &config);
504        assert!(result.is_err());
505    }
506
507    #[test]
508    fn test_build_drawing_with_new_format() {
509        let config = ImageConfig {
510            data: vec![0x42, 0x4D],
511            format: ImageFormat::Bmp,
512            from_cell: "D4".to_string(),
513            width_px: 320,
514            height_px: 240,
515        };
516
517        let dr = build_drawing_with_image("rId1", &config).unwrap();
518        assert_eq!(dr.one_cell_anchors.len(), 1);
519        let anchor = &dr.one_cell_anchors[0];
520        assert_eq!(anchor.from.col, 3);
521        assert_eq!(anchor.from.row, 3);
522        assert_eq!(anchor.ext.cx, 320 * 9525);
523        assert_eq!(anchor.ext.cy, 240 * 9525);
524    }
525
526    #[test]
527    fn test_validate_image_config_ok() {
528        let config = ImageConfig {
529            data: vec![1, 2, 3],
530            format: ImageFormat::Png,
531            from_cell: "A1".to_string(),
532            width_px: 100,
533            height_px: 100,
534        };
535        assert!(validate_image_config(&config).is_ok());
536    }
537
538    #[test]
539    fn test_validate_image_config_new_format_ok() {
540        let config = ImageConfig {
541            data: vec![1, 2, 3],
542            format: ImageFormat::Svg,
543            from_cell: "A1".to_string(),
544            width_px: 100,
545            height_px: 100,
546        };
547        assert!(validate_image_config(&config).is_ok());
548    }
549
550    #[test]
551    fn test_validate_image_config_empty_data() {
552        let config = ImageConfig {
553            data: vec![],
554            format: ImageFormat::Png,
555            from_cell: "A1".to_string(),
556            width_px: 100,
557            height_px: 100,
558        };
559        assert!(validate_image_config(&config).is_err());
560    }
561
562    #[test]
563    fn test_validate_image_config_zero_width() {
564        let config = ImageConfig {
565            data: vec![1],
566            format: ImageFormat::Png,
567            from_cell: "A1".to_string(),
568            width_px: 0,
569            height_px: 100,
570        };
571        assert!(validate_image_config(&config).is_err());
572    }
573
574    #[test]
575    fn test_validate_image_config_zero_height() {
576        let config = ImageConfig {
577            data: vec![1],
578            format: ImageFormat::Png,
579            from_cell: "A1".to_string(),
580            width_px: 100,
581            height_px: 0,
582        };
583        assert!(validate_image_config(&config).is_err());
584    }
585
586    #[test]
587    fn test_validate_image_config_invalid_cell() {
588        let config = ImageConfig {
589            data: vec![1],
590            format: ImageFormat::Png,
591            from_cell: "ZZZZZ0".to_string(),
592            width_px: 100,
593            height_px: 100,
594        };
595        assert!(validate_image_config(&config).is_err());
596    }
597
598    #[test]
599    fn test_add_image_to_existing_drawing() {
600        let mut dr = WsDr::default();
601
602        let config = ImageConfig {
603            data: vec![1, 2, 3],
604            format: ImageFormat::Png,
605            from_cell: "C5".to_string(),
606            width_px: 200,
607            height_px: 150,
608        };
609
610        add_image_to_drawing(&mut dr, "rId3", &config, 3).unwrap();
611
612        assert_eq!(dr.one_cell_anchors.len(), 1);
613        let anchor = &dr.one_cell_anchors[0];
614        assert_eq!(anchor.from.col, 2);
615        assert_eq!(anchor.from.row, 4);
616        assert_eq!(
617            anchor.pic.as_ref().unwrap().nv_pic_pr.c_nv_pr.name,
618            "Picture 2"
619        );
620    }
621
622    #[test]
623    fn test_emu_calculation_accuracy() {
624        assert_eq!(pixels_to_emu(96), 914400);
625    }
626}