orbtk_render/raqote/
image.rs

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