From 93dc08a3bf7fd4ff26148ba8ce2c3bf190011053 Mon Sep 17 00:00:00 2001 From: Igor Strebz Date: Fri, 13 Sep 2024 12:26:18 +0300 Subject: [PATCH] Speed up image stuff (#223) * Get the dimensions without reading the full image into memory This is faster than fully loading the image and then getting its dimensions. * Introduce a way to insert images as a byte buffer --- Cargo.toml | 5 +++-- src/structs/image.rs | 23 +++++++++++++---------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index cfdb4aaf..2728870a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "umya-spreadsheet" -version = "2.0.2" +version = "2.0.3" authors = ["MathNya "] repository = "https://github.com/MathNya/umya-spreadsheet" keywords = ["excel", "spreadsheet", "xlsx", "reader", "writer"] @@ -24,7 +24,7 @@ getrandom = { version = "0.2.14" } hashbrown = "0.14.3" hmac = "0.12.1" html_parser = "0.7.0" -image = "0.25.0" +image = { version = "0.25.0", optional = true } lazy_static = "1.4.0" md-5 = "0.10.6" regex = "1.10.2" @@ -38,3 +38,4 @@ doctest = false [features] js = ["getrandom/js"] +default = ["image"] diff --git a/src/structs/image.rs b/src/structs/image.rs index d9f8eeb7..bcd47e95 100644 --- a/src/structs/image.rs +++ b/src/structs/image.rs @@ -1,10 +1,10 @@ use base64::{engine::general_purpose::STANDARD, Engine as _}; -use image::GenericImageView; use quick_xml::Writer; use std::fs; use std::fs::File; use std::io::Cursor; use std::io::Read; +use std::io::BufReader; use structs::drawing::spreadsheet::MarkerType; use structs::drawing::spreadsheet::OneCellAnchor; use structs::drawing::spreadsheet::Picture; @@ -97,18 +97,21 @@ impl Image { self } + #[cfg(feature = "image")] pub fn new_image(&mut self, path: &str, marker: MarkerType) { - let path_str = path; - let path_obj = std::path::Path::new(path_str); - let image_name = path_obj.file_name().unwrap().to_str().unwrap(); + let path = std::path::Path::new(path); - let img = image::open(path_obj).unwrap(); - let (width, height) = img.dimensions(); - - let mut file = File::open(path_str).unwrap(); + let (width, height) = image::image_dimensions(path).unwrap(); + let image_name = path.file_name().unwrap().to_str().unwrap(); let mut buf = Vec::new(); - file.read_to_end(&mut buf).unwrap(); + let file = File::open(path).unwrap(); + BufReader::new(file).read_to_end(&mut buf).unwrap(); + + self.new_image_with_dimensions(height, width, image_name, buf, marker) + } + + pub fn new_image_with_dimensions>>(&mut self, height: u32, width: u32, image_name: &str, bytes: B, marker: MarkerType) { let mut picture = Picture::default(); // filename and filedata. picture @@ -117,7 +120,7 @@ impl Image { .set_cstate("print") .get_image_mut() .set_image_name(image_name) - .set_image_data(buf); + .set_image_data(bytes.into()); // name picture