orbtk_tinyskia/tinyskia/
image.rs

1use std::{fmt, path::Path};
2
3use crate::RenderTarget;
4
5/// Structure that defines elements of an image object.
6#[derive(Clone, Default)]
7pub struct Image {
8    render_target: RenderTarget,
9    source: String,
10}
11
12impl fmt::Debug for Image {
13    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
14        write!(f, "Image ( source: {})", self.source)
15    }
16}
17
18impl std::cmp::PartialEq for Image {
19    fn eq(&self, other: &Self) -> bool {
20        self.source == other.source
21    }
22}
23
24impl Image {
25    /// Creates a new image with the given width and height.
26    pub fn new(width: u32, height: u32) -> Self {
27        Image {
28            render_target: RenderTarget::new(width, height),
29            source: String::default(),
30        }
31    }
32
33    /// Draws a u32 slice into the image.
34    pub fn draw(&mut self, data: &[u32]) {
35        self.render_target.data.clone_from_slice(data);
36    }
37
38    /// Create a new image from a boxed slice of colors
39    pub fn from_data(width: u32, height: u32, data: Vec<u32>) -> Result<Self, String> {
40        Ok(Image {
41            render_target: RenderTarget::from_data(width, height, data).unwrap(),
42            source: String::new(),
43        })
44    }
45
46    /// Creates a new image from an `RgbaImage`.
47    pub fn from_rgba_image(image: image::RgbaImage) -> Result<Self, String> {
48        let data: Vec<u32> = image
49            .pixels()
50            .map(|p| {
51                ((p[3] as u32) << 24) | ((p[0] as u32) << 16) | ((p[1] as u32) << 8) | (p[2] as u32)
52            })
53            .collect();
54        Self::from_data(image.width(), image.height(), data)
55    }
56
57    /// Load an image from file path. Supports BMP and PNG
58    pub fn from_path<P: AsRef<Path> + std::fmt::Debug + Clone>(path: P) -> Result<Self, String> {
59        let img = image::open(path.clone());
60
61        if let Ok(img) = img {
62            return Self::from_rgba_image(img.to_rgba8());
63        }
64
65        Err(format!("Could not load image width path: {:?}", path))
66    }
67
68    /// Gets the width.
69    pub fn width(&self) -> f64 {
70        self.render_target.width() as f64
71    }
72
73    /// Gets the height.
74    pub fn height(&self) -> f64 {
75        self.render_target.height() as f64
76    }
77
78    pub fn data(&self) -> &[u32] {
79        &self.render_target.data
80    }
81
82    pub fn data_mut(&mut self) -> &mut [u32] {
83        &mut self.render_target.data
84    }
85}
86
87impl From<(u32, u32, Vec<u32>)> for Image {
88    fn from(image: (u32, u32, Vec<u32>)) -> Self {
89        Image::from_data(image.0, image.1, image.2).unwrap()
90    }
91}
92
93pub fn os_path(path: String) -> String {
94    if cfg!(windows) {
95        path.replace("/", "\\")
96    } else {
97        path.replace("\\", "/")
98    }
99}
100
101// --- Conversions ---
102
103impl From<&str> for Image {
104    fn from(s: &str) -> Image {
105        Image::from_path(os_path(s.to_string())).unwrap()
106    }
107}
108
109impl From<String> for Image {
110    fn from(s: String) -> Image {
111        Image::from_path(os_path(s)).unwrap()
112    }
113}
114
115// --- Conversions ---