1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#[cfg(feature = "images")]

use std::path::Path;

use image;
use crate::shape::{Color, Shape};
use crate::error::Result;


/// Image shape. Can be created from any file, [`image`] crate can parse. Supports transparency
pub struct Image {
    image: image::RgbaImage
}

impl Image {
    /// Create [`Image`] from file
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
        Ok(Self { image: image::open(path)?.to_rgba() })
    }

    /// Create [`Image`] from in-memory buffer
    pub fn from_buffer(buffer: &[u8]) -> Result<Self> {
        Ok(Self { image: image::load_from_memory(buffer)?.to_rgba() })
    }
}

impl Shape for Image {
    fn render(&self) -> Vec<Vec<Option<Color>>> {
        self.image.rows().map(|row| {
            row.map(|rgba| {
                let [r, g, b, a] = rgba.0;
                if a == 0 {
                    None
                } else {
                    Some((r, g, b, a).into())
                }
            }).collect()
        }).collect()
    }
}