Newer
Older
use crate::commands::palette::ColourMapping;
use clap::Parser;
use image::{GenericImage, Pixel, Rgba};
use num_traits::ToPrimitive;
/// Convert the colour space of an image to that of a given palette file
#[derive(Debug, Clone, Parser, Serialize, Deserialize)]
#[clap(author, version = "0.3.0")]
pub struct Remap {
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
#[serde(default)]
pub output: String,
/// The path to the palette file containing the output colours
#[clap(short, long)]
pub palette: String,
}
impl Remap {
pub fn remap_image(
image: impl GenericImage,
mappings: ColourMapping,
) -> anyhow::Result<OutputFormat> {
let mut output = new_image(image.width(), image.height());
for (x, y, pixel) in image.pixels() {
let pixel = pixel.to_rgba();
if pixel.0[3].to_u8().unwrap() == 0 {
output.put_pixel(x, y, Rgba::from(BasicRgba::transparent()));
continue;
}
let data = Rgba::from([
pixel.0[0].to_u8().unwrap(),
pixel.0[1].to_u8().unwrap(),
pixel.0[2].to_u8().unwrap(),
pixel.0[3].to_u8().unwrap(),
]);
let basic = BasicRgba::from(data);
match mappings.get(&basic) {
Some(mapped_data) => output.put_pixel(
x,
y,
Rgba::from(BasicRgba {
a: basic.a,
..*mapped_data
}),
),
None => output.put_pixel(x, y, Rgba::from(BasicRgba::transparent())),
};