pub mod png;
pub mod ppm;
pub mod raw;
use clap::ValueEnum;
use webpkit::lossless::{Image, Metadata, PixelLayout};
use crate::{error::CliError, format::raw::RawParams};
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum InputFormat {
Png,
Ppm,
Pam,
Raw,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
Png,
Ppm,
Pam,
Raw,
}
impl InputFormat {
#[must_use]
pub fn resolve(explicit: Option<Self>, extension: Option<&str>, bytes: &[u8]) -> Self {
explicit
.or_else(|| extension.and_then(Self::from_extension))
.or_else(|| Self::sniff(bytes))
.unwrap_or(Self::Raw)
}
fn from_extension(ext: &str) -> Option<Self> {
match ext {
"png" => Some(Self::Png),
"ppm" => Some(Self::Ppm),
"pam" => Some(Self::Pam),
"raw" | "rgba" | "argb" | "bgra" => Some(Self::Raw),
_ => None,
}
}
fn sniff(bytes: &[u8]) -> Option<Self> {
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
Some(Self::Png)
} else if bytes.starts_with(b"P6") {
Some(Self::Ppm)
} else if bytes.starts_with(b"P7") {
Some(Self::Pam)
} else {
None
}
}
}
impl OutputFormat {
#[must_use]
pub fn resolve(explicit: Option<Self>, extension: Option<&str>) -> Self {
explicit
.or_else(|| extension.and_then(Self::from_extension))
.unwrap_or(Self::Png)
}
fn from_extension(ext: &str) -> Option<Self> {
match ext {
"png" => Some(Self::Png),
"ppm" => Some(Self::Ppm),
"pam" => Some(Self::Pam),
"raw" | "rgba" | "argb" | "bgra" => Some(Self::Raw),
_ => None,
}
}
}
pub fn read_image(
bytes: &[u8],
format: InputFormat,
raw: Option<RawParams>,
) -> Result<Image, CliError> {
match format {
InputFormat::Png => png::read(bytes),
InputFormat::Ppm | InputFormat::Pam => ppm::read(bytes),
InputFormat::Raw => {
let params = raw.ok_or_else(|| {
CliError::RawConfig(
"raw input requires --width and --height (or use a PNG/PPM/PAM file)"
.to_owned(),
)
})?;
raw::read(bytes, params)
},
}
}
pub fn write_image(
image: &Image,
format: OutputFormat,
metadata: &Metadata,
) -> Result<Vec<u8>, CliError> {
match format {
OutputFormat::Png => png::write(image, metadata),
OutputFormat::Ppm => Ok(ppm::write_ppm(image)),
OutputFormat::Pam => Ok(ppm::write_pam(image)),
OutputFormat::Raw => Ok(image.as_bytes().to_vec()),
}
}
#[must_use]
pub fn to_rgba8(image: &Image) -> Vec<u8> {
let src = image.as_bytes();
match image.layout() {
PixelLayout::Rgba8 => src.to_vec(),
PixelLayout::Argb8 => reorder(src, [1, 2, 3, 0]),
PixelLayout::Bgra8 => reorder(src, [2, 1, 0, 3]),
}
}
fn reorder(src: &[u8], order: [usize; 4]) -> Vec<u8> {
let mut out = Vec::with_capacity(src.len());
for px in src.chunks_exact(4) {
out.extend_from_slice(&[px[order[0]], px[order[1]], px[order[2]], px[order[3]]]);
}
out
}