1use std::path::Path;
6use crate::core::{Positioned, ElementSized};
7
8fn format_and_ext(format: &str) -> (String, String) {
10 let upper = format.to_uppercase();
11 let ext = match upper.as_str() {
12 "JPEG" => "jpg".to_string(),
13 _ => upper.to_lowercase(),
14 };
15 (upper, ext)
16}
17
18fn generate_image_filename(format: &str) -> (String, String) {
20 let (upper, ext) = format_and_ext(format);
21 let filename = format!("image_{}.{}", uuid::Uuid::new_v4(), ext);
22 (filename, upper)
23}
24
25#[derive(Clone, Debug)]
27pub enum ImageSource {
28 File(String),
30 Base64(String),
32 Bytes(Vec<u8>),
34 #[cfg(feature = "web2ppt")]
36 Url(String),
37}
38
39#[derive(Clone, Debug, Default)]
41pub struct Crop {
42 pub left: f64,
43 pub top: f64,
44 pub right: f64,
45 pub bottom: f64,
46}
47
48impl Crop {
49 pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Self {
51 Self { left, top, right, bottom }
52 }
53}
54
55#[derive(Clone, Debug)]
57pub enum ImageEffect {
58 Shadow,
60 Reflection,
62}
63
64#[derive(Clone, Debug)]
66pub struct Image {
67 pub filename: String,
68 pub width: u32, pub height: u32, pub x: u32, pub y: u32, pub format: String, pub source: Option<ImageSource>,
75 pub crop: Option<Crop>,
77 pub effects: Vec<ImageEffect>,
79}
80
81impl Image {
82 pub fn new(filename: &str, width: u32, height: u32, format: &str) -> Self {
84 Image {
85 filename: filename.to_string(),
86 width,
87 height,
88 x: 0,
89 y: 0,
90 format: format.to_uppercase(),
91 source: Some(ImageSource::File(filename.to_string())),
92 crop: None,
93 effects: Vec::new(),
94 }
95 }
96
97 pub fn from_path<P: AsRef<Path>>(path: P) -> std::result::Result<Self, String> {
99 let path = path.as_ref();
100 let filename = path.file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "image.png".to_string());
101 let path_str = path.to_string_lossy().to_string();
102
103 let data = std::fs::read(path)
104 .map_err(|e| format!("Failed to open image: {e}"))?;
105 let (w, h, format) = read_image_dimensions(&data)
106 .ok_or_else(|| "Failed to detect image dimensions (unsupported format)".to_string())?;
107
108 let w_emu = w * 9525;
110 let h_emu = h * 9525;
111
112 Ok(Image {
113 filename,
114 width: w_emu,
115 height: h_emu,
116 x: 0,
117 y: 0,
118 format,
119 source: Some(ImageSource::File(path_str)),
120 crop: None,
121 effects: Vec::new(),
122 })
123 }
124
125 pub fn from_base64(data: &str, width: u32, height: u32, format: &str) -> Self {
140 let (filename, fmt) = generate_image_filename(format);
141 Self::with_source(filename, width, height, fmt, ImageSource::Base64(data.to_string()))
142 }
143
144 pub fn from_bytes(data: Vec<u8>, width: u32, height: u32, format: &str) -> Self {
146 let (filename, fmt) = generate_image_filename(format);
147 Self::with_source(filename, width, height, fmt, ImageSource::Bytes(data))
148 }
149
150 #[cfg(feature = "web2ppt")]
152 pub fn from_url(url: &str, width: u32, height: u32, format: &str) -> Self {
153 let (filename, fmt) = generate_image_filename(format);
154 Self::with_source(filename, width, height, fmt, ImageSource::Url(url.to_string()))
155 }
156
157 fn with_source(filename: String, width: u32, height: u32, format: String, source: ImageSource) -> Self {
159 Image {
160 filename,
161 width,
162 height,
163 x: 0,
164 y: 0,
165 format,
166 source: Some(source),
167 crop: None,
168 effects: Vec::new(),
169 }
170 }
171
172 pub fn get_bytes(&self) -> Option<Vec<u8>> {
174 match &self.source {
175 Some(ImageSource::Base64(data)) => {
176 base64_decode(data).ok()
178 }
179 Some(ImageSource::Bytes(data)) => Some(data.clone()),
180 Some(ImageSource::File(path)) => {
181 std::fs::read(path).ok()
182 }
183 #[cfg(feature = "web2ppt")]
184 Some(ImageSource::Url(url)) => {
185 let client = reqwest::blocking::Client::builder()
188 .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
189 .build()
190 .ok()?;
191
192 match client.get(url).send() {
193 Ok(resp) => {
194 if resp.status().is_success() {
195 resp.bytes().ok().map(|b| b.to_vec())
196 } else {
197 None
198 }
199 },
200 Err(_) => None,
201 }
202 }
203 None => None,
204 }
205 }
206
207 pub fn position(mut self, x: u32, y: u32) -> Self {
209 self.x = x;
210 self.y = y;
211 self
212 }
213
214 pub fn with_crop(mut self, left: f64, top: f64, right: f64, bottom: f64) -> Self {
216 self.crop = Some(Crop::new(left, top, right, bottom));
217 self
218 }
219
220 pub fn with_effect(mut self, effect: ImageEffect) -> Self {
222 self.effects.push(effect);
223 self
224 }
225
226 pub fn aspect_ratio(&self) -> f64 {
228 self.width as f64 / self.height as f64
229 }
230
231 pub fn scale_to_width(mut self, width: u32) -> Self {
233 let ratio = self.aspect_ratio();
234 self.width = width;
235 self.height = (width as f64 / ratio) as u32;
236 self
237 }
238
239 pub fn scale_to_height(mut self, height: u32) -> Self {
241 let ratio = self.aspect_ratio();
242 self.height = height;
243 self.width = (height as f64 * ratio) as u32;
244 self
245 }
246
247 pub fn extension(&self) -> String {
249 Path::new(&self.filename)
250 .extension()
251 .and_then(|ext| ext.to_str())
252 .map(|s| s.to_lowercase())
253 .unwrap_or_else(|| self.format.to_lowercase())
254 }
255
256 pub fn mime_type(&self) -> String {
258 match self.format.as_str() {
259 "PNG" => "image/png".to_string(),
260 "JPG" | "JPEG" => "image/jpeg".to_string(),
261 "GIF" => "image/gif".to_string(),
262 "BMP" => "image/bmp".to_string(),
263 "TIFF" => "image/tiff".to_string(),
264 "SVG" => "image/svg+xml".to_string(),
265 _ => "application/octet-stream".to_string(),
266 }
267 }
268}
269
270impl Positioned for Image {
271 fn x(&self) -> u32 { self.x }
272 fn y(&self) -> u32 { self.y }
273 fn set_position(&mut self, x: u32, y: u32) {
274 self.x = x;
275 self.y = y;
276 }
277}
278
279impl ElementSized for Image {
280 fn width(&self) -> u32 { self.width }
281 fn height(&self) -> u32 { self.height }
282 fn set_size(&mut self, width: u32, height: u32) {
283 self.width = width;
284 self.height = height;
285 }
286}
287
288fn base64_decode(input: &str) -> Result<Vec<u8>, std::io::Error> {
290 const DECODE_TABLE: [i8; 128] = [
292 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
293 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
294 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
295 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
296 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
297 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
298 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
299 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
300 ];
301
302 let input = input.trim().replace(['\n', '\r', ' '], "");
303 let mut output = Vec::with_capacity(input.len() * 3 / 4);
304 let bytes: Vec<u8> = input.bytes().collect();
305
306 let mut i = 0;
307 while i < bytes.len() {
308 let mut buf = [0u8; 4];
309 let mut pad = 0;
310
311 for j in 0..4 {
312 if i + j >= bytes.len() || bytes[i + j] == b'=' {
313 buf[j] = 0;
314 pad += 1;
315 } else if bytes[i + j] < 128 && DECODE_TABLE[bytes[i + j] as usize] >= 0 {
316 buf[j] = DECODE_TABLE[bytes[i + j] as usize] as u8;
317 } else {
318 return Err(std::io::Error::new(
319 std::io::ErrorKind::InvalidData,
320 "Invalid base64 character",
321 ));
322 }
323 }
324
325 output.push((buf[0] << 2) | (buf[1] >> 4));
326 if pad < 2 {
327 output.push((buf[1] << 4) | (buf[2] >> 2));
328 }
329 if pad < 1 {
330 output.push((buf[2] << 6) | buf[3]);
331 }
332
333 i += 4;
334 }
335
336 Ok(output)
337}
338
339pub struct ImageBuilder {
341 filename: String,
342 width: u32,
343 height: u32,
344 x: u32,
345 y: u32,
346 format: String,
347 source: Option<ImageSource>,
348}
349
350impl ImageBuilder {
351 pub fn new(filename: &str, width: u32, height: u32) -> Self {
353 let format = Path::new(filename)
354 .extension()
355 .and_then(|ext| ext.to_str())
356 .map(|s| s.to_uppercase())
357 .unwrap_or_else(|| "PNG".to_string());
358
359 ImageBuilder {
360 filename: filename.to_string(),
361 width,
362 height,
363 x: 0,
364 y: 0,
365 format,
366 source: Some(ImageSource::File(filename.to_string())),
367 }
368 }
369
370 pub fn from_base64(data: &str, width: u32, height: u32, format: &str) -> Self {
372 let (upper, ext) = format_and_ext(format);
373 ImageBuilder {
374 filename: format!("image.{}", ext),
375 width, height, x: 0, y: 0,
376 format: upper,
377 source: Some(ImageSource::Base64(data.to_string())),
378 }
379 }
380
381 pub fn from_bytes(data: Vec<u8>, width: u32, height: u32, format: &str) -> Self {
383 let (upper, ext) = format_and_ext(format);
384 ImageBuilder {
385 filename: format!("image.{}", ext),
386 width, height, x: 0, y: 0,
387 format: upper,
388 source: Some(ImageSource::Bytes(data)),
389 }
390 }
391
392 pub fn position(mut self, x: u32, y: u32) -> Self {
394 self.x = x;
395 self.y = y;
396 self
397 }
398
399 pub fn format(mut self, format: &str) -> Self {
401 self.format = format.to_uppercase();
402 self
403 }
404
405 pub fn scale_to_width(mut self, width: u32) -> Self {
407 let ratio = self.width as f64 / self.height as f64;
408 self.width = width;
409 self.height = (width as f64 / ratio) as u32;
410 self
411 }
412
413 pub fn scale_to_height(mut self, height: u32) -> Self {
415 let ratio = self.width as f64 / self.height as f64;
416 self.height = height;
417 self.width = (height as f64 * ratio) as u32;
418 self
419 }
420
421 pub fn build(self) -> Image {
423 Image {
424 filename: self.filename,
425 width: self.width,
426 height: self.height,
427 x: self.x,
428 y: self.y,
429 format: self.format,
430 source: self.source,
431 crop: None,
432 effects: Vec::new(),
433 }
434 }
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
442 fn test_image_creation() {
443 let img = Image::new("test.png", 1920, 1080, "PNG");
444 assert_eq!(img.filename, "test.png");
445 assert_eq!(img.width, 1920);
446 assert_eq!(img.height, 1080);
447 }
448
449 #[test]
450 fn test_image_position() {
451 let img = Image::new("test.png", 1920, 1080, "PNG")
452 .position(500000, 1000000);
453 assert_eq!(img.x, 500000);
454 assert_eq!(img.y, 1000000);
455 }
456
457 #[test]
458 fn test_image_aspect_ratio() {
459 let img = Image::new("test.png", 1920, 1080, "PNG");
460 let ratio = img.aspect_ratio();
461 assert!((ratio - 1.777).abs() < 0.01);
462 }
463
464 #[test]
465 fn test_image_scale_to_width() {
466 let img = Image::new("test.png", 1920, 1080, "PNG")
467 .scale_to_width(960);
468 assert_eq!(img.width, 960);
469 assert_eq!(img.height, 540);
470 }
471
472 #[test]
473 fn test_image_scale_to_height() {
474 let img = Image::new("test.png", 1920, 1080, "PNG")
475 .scale_to_height(540);
476 assert_eq!(img.width, 960);
477 assert_eq!(img.height, 540);
478 }
479
480 #[test]
481 fn test_image_extension() {
482 let img = Image::new("photo.jpg", 1920, 1080, "JPEG");
483 assert_eq!(img.extension(), "jpg");
484 }
485
486 #[test]
487 fn test_image_mime_types() {
488 assert_eq!(
489 Image::new("test.png", 100, 100, "PNG").mime_type(),
490 "image/png"
491 );
492 assert_eq!(
493 Image::new("test.jpg", 100, 100, "JPG").mime_type(),
494 "image/jpeg"
495 );
496 assert_eq!(
497 Image::new("test.gif", 100, 100, "GIF").mime_type(),
498 "image/gif"
499 );
500 }
501
502 #[test]
503 fn test_image_builder() {
504 let img = ImageBuilder::new("photo.png", 1920, 1080)
505 .position(500000, 1000000)
506 .scale_to_width(960)
507 .build();
508
509 assert_eq!(img.filename, "photo.png");
510 assert_eq!(img.width, 960);
511 assert_eq!(img.height, 540);
512 assert_eq!(img.x, 500000);
513 assert_eq!(img.y, 1000000);
514 }
515
516 #[test]
517 fn test_image_builder_auto_format() {
518 let img = ImageBuilder::new("photo.jpg", 1920, 1080).build();
519 assert_eq!(img.format, "JPG");
520 }
521
522 #[test]
523 fn test_image_from_base64() {
524 let base64_png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
526 let img = Image::from_base64(base64_png, 100, 100, "PNG");
527
528 assert!(img.filename.ends_with(".png"));
529 assert_eq!(img.format, "PNG");
530 assert!(matches!(img.source, Some(ImageSource::Base64(_))));
531 }
532
533 #[test]
534 fn test_image_from_bytes() {
535 let data = vec![0x89, 0x50, 0x4E, 0x47]; let img = Image::from_bytes(data.clone(), 100, 100, "PNG");
537
538 assert_eq!(img.format, "PNG");
539 assert!(matches!(img.source, Some(ImageSource::Bytes(_))));
540 }
541
542 #[test]
543 fn test_base64_decode() {
544 let result = base64_decode("SGVsbG8=").unwrap();
546 assert_eq!(result, b"Hello");
547
548 let result = base64_decode("SGVsbG8gV29ybGQ=").unwrap();
550 assert_eq!(result, b"Hello World");
551 }
552
553 #[test]
554 fn test_image_get_bytes_base64() {
555 let base64_png = "SGVsbG8="; let img = Image::from_base64(base64_png, 100, 100, "PNG");
557
558 let bytes = img.get_bytes().unwrap();
559 assert_eq!(bytes, b"Hello");
560 }
561
562 #[test]
563 fn test_image_builder_from_base64() {
564 let base64_data = "SGVsbG8=";
565 let img = ImageBuilder::from_base64(base64_data, 200, 150, "JPEG")
566 .position(1000, 2000)
567 .build();
568
569 assert_eq!(img.width, 200);
570 assert_eq!(img.height, 150);
571 assert_eq!(img.x, 1000);
572 assert_eq!(img.y, 2000);
573 assert_eq!(img.format, "JPEG");
574 }
575
576 #[test]
577 fn test_read_png_dimensions() {
578 let png: Vec<u8> = vec![
580 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, ];
587 let (w, h, fmt) = read_image_dimensions(&png).unwrap();
588 assert_eq!((w, h), (1, 1));
589 assert_eq!(fmt, "PNG");
590 }
591
592 #[test]
593 fn test_read_gif_dimensions() {
594 let gif: Vec<u8> = vec![
595 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x0A, 0x00, 0x14, 0x00, ];
599 let (w, h, fmt) = read_image_dimensions(&gif).unwrap();
600 assert_eq!((w, h), (10, 20));
601 assert_eq!(fmt, "GIF");
602 }
603
604 #[test]
605 fn test_read_bmp_dimensions() {
606 let mut bmp = vec![0u8; 26];
607 bmp[0] = 0x42; bmp[1] = 0x4D; bmp[18..22].copy_from_slice(&100u32.to_le_bytes()); bmp[22..26].copy_from_slice(&200u32.to_le_bytes()); let (w, h, fmt) = read_image_dimensions(&bmp).unwrap();
611 assert_eq!((w, h), (100, 200));
612 assert_eq!(fmt, "BMP");
613 }
614}
615
616fn read_image_dimensions(data: &[u8]) -> Option<(u32, u32, String)> {
619 if data.len() < 10 {
620 return None;
621 }
622 if data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) && data.len() >= 24 {
624 let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
625 let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
626 return Some((w, h, "PNG".into()));
627 }
628 if data.starts_with(&[0xFF, 0xD8]) {
630 return read_jpeg_dimensions(data);
631 }
632 if data.starts_with(b"GIF8") && data.len() >= 10 {
634 let w = u16::from_le_bytes([data[6], data[7]]) as u32;
635 let h = u16::from_le_bytes([data[8], data[9]]) as u32;
636 return Some((w, h, "GIF".into()));
637 }
638 if data.starts_with(b"BM") && data.len() >= 26 {
640 let w = u32::from_le_bytes([data[18], data[19], data[20], data[21]]);
641 let h = u32::from_le_bytes([data[22], data[23], data[24], data[25]]);
642 return Some((w, h, "BMP".into()));
643 }
644 if data.len() >= 30 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
646 if &data[12..16] == b"VP8 " && data.len() >= 30 {
648 let w = u16::from_le_bytes([data[26], data[27]]) as u32 & 0x3FFF;
649 let h = u16::from_le_bytes([data[28], data[29]]) as u32 & 0x3FFF;
650 return Some((w, h, "WEBP".into()));
651 }
652 if &data[12..16] == b"VP8L" && data.len() >= 25 {
654 let b0 = data[21] as u32;
655 let b1 = data[22] as u32;
656 let b2 = data[23] as u32;
657 let b3 = data[24] as u32;
658 let bits = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
659 let w = (bits & 0x3FFF) + 1;
660 let h = ((bits >> 14) & 0x3FFF) + 1;
661 return Some((w, h, "WEBP".into()));
662 }
663 }
664 None
665}
666
667fn read_jpeg_dimensions(data: &[u8]) -> Option<(u32, u32, String)> {
669 let mut i = 2;
670 while i + 1 < data.len() {
671 if data[i] != 0xFF {
672 i += 1;
673 continue;
674 }
675 let marker = data[i + 1];
676 i += 2;
677 if (marker == 0xC0 || marker == 0xC2) && i + 7 < data.len() {
679 let h = u16::from_be_bytes([data[i + 3], data[i + 4]]) as u32;
680 let w = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
681 return Some((w, h, "JPEG".into()));
682 }
683 if marker >= 0xC0 && marker != 0xD9 && marker != 0xDA && i + 1 < data.len() {
685 let len = u16::from_be_bytes([data[i], data[i + 1]]) as usize;
686 i += len;
687 }
688 }
689 None
690}