use std::path::PathBuf;
#[derive(Clone, Debug, PartialEq)]
pub enum ImageFormat {
Png,
Jpeg,
Gif,
Emf,
Wmf,
Bmp,
Tiff,
}
impl ImageFormat {
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",
}
}
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",
}
}
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,
}
}
pub fn from_bytes(data: &[u8]) -> Option<Self> {
if data.len() < 8 {
return None;
}
if data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
return Some(ImageFormat::Png);
}
if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
return Some(ImageFormat::Jpeg);
}
if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
return Some(ImageFormat::Gif);
}
if data.starts_with(b"BM") {
return Some(ImageFormat::Bmp);
}
if data.starts_with(&[0x49, 0x49, 0x2A, 0x00])
|| data.starts_with(&[0x4D, 0x4D, 0x00, 0x2A])
{
return Some(ImageFormat::Tiff);
}
None
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ImageAnchorType {
OneCell,
TwoCell,
Absolute,
}
#[derive(Clone, Debug)]
pub struct ImageAnchor {
pub anchor_type: ImageAnchorType,
pub from_cell: String,
pub from_col_offset: u32,
pub from_row_offset: u32,
pub to_cell: Option<String>,
pub to_col_offset: u32,
pub to_row_offset: u32,
}
impl ImageAnchor {
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,
}
}
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,
}
}
pub fn with_offset_px(mut self, col_px: u32, row_px: u32) -> Self {
self.from_col_offset = col_px * 9525;
self.from_row_offset = row_px * 9525;
self
}
}
#[derive(Clone, Debug)]
pub struct Image {
pub data: Vec<u8>,
pub format: ImageFormat,
pub source_path: Option<PathBuf>,
pub anchor: ImageAnchor,
pub width: u32,
pub height: u32,
pub alt_text: Option<String>,
pub description: Option<String>,
pub name: Option<String>,
}
impl Image {
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, height: 914400, alt_text: None,
description: None,
name: None,
})
}
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,
})
}
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
}
pub fn with_size_px(mut self, width: u32, height: u32) -> Self {
self.width = width * 9525;
self.height = height * 9525;
self
}
pub fn with_alt_text<S: Into<String>>(mut self, text: S) -> Self {
self.alt_text = Some(text.into());
self
}
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() {
let png_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
assert_eq!(ImageFormat::from_bytes(&png_data), Some(ImageFormat::Png));
let jpeg_data = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46];
assert_eq!(ImageFormat::from_bytes(&jpeg_data), Some(ImageFormat::Jpeg));
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); assert_eq!(image.height, 1371600); }
#[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); assert_eq!(ImageFormat::from_bytes(&[0; 8]), None); }
#[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"));
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);
}
}