about summary refs log tree commit diff
path: root/src/colorimage.rs
blob: 1bdb273e5c1145342b124ebcb9ebd615ff516245 (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use std::convert::TryFrom;

use crate::{block::ColorTable, gif::Image, reader::DecodingError, Color};

pub struct ColorImage {
    width: u16,
    height: u16,
    data: Vec<Pixel>,
}

impl ColorImage {
    pub(crate) fn from_indicies(
        width: u16,
        height: u16,
        indicies: &[u8],
        table: &ColorTable,
        transindex: Option<u8>,
    ) -> Result<Self, DecodingError> {
        let mut data = vec![Pixel::Transparent; (width * height) as usize];

        for (image_index, color_index) in indicies.into_iter().enumerate() {
            if let Some(trans) = transindex {
                if trans == *color_index {
                    data[image_index] = Pixel::Transparent;
                }
            } else {
                data[image_index] = Pixel::Color(
                    table
                        .get(*color_index)
                        .ok_or(DecodingError::ColorIndexOutOfBounds)?,
                );
            }
        }

        Ok(ColorImage {
            width,
            height,
            data,
        })
    }
}

impl<'a> TryFrom<Image<'a>> for ColorImage {
    type Error = DecodingError;

    fn try_from(img: Image<'a>) -> Result<Self, Self::Error> {
        ColorImage::from_indicies(
            img.width,
            img.height,
            img.indicies,
            img.palette,
            img.transparent_index,
        )
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Pixel {
    Color(Color),
    Transparent,
}