use std::{fmt, fs, io, path::Path};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use image::codecs::{jpeg::JpegEncoder, png::PngEncoder};
use image::{ExtendedColorType, ImageEncoder, RgbaImage};
use thiserror::Error;
use crate::Size;
const DEFAULT_JPEG_QUALITY: u8 = 100;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Format {
Jpeg,
Png,
}
impl Format {
#[must_use]
pub const fn media_type(self) -> &'static str {
match self {
Self::Jpeg => "image/jpeg",
Self::Png => "image/png",
}
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ImageError {
#[error("JPEG quality must be in 1..=100, got {0}")]
InvalidQuality(u8),
#[error("could not encode image")]
Encode(#[from] image::ImageError),
#[error("could not write image to {path}", path = .path.display())]
Write {
path: std::path::PathBuf,
#[source]
source: io::Error,
},
}
#[derive(Clone)]
pub struct Image {
pixels: RgbaImage,
format: Format,
}
impl fmt::Debug for Image {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Image")
.field("format", &self.format)
.field("size", &self.size())
.finish_non_exhaustive()
}
}
impl Image {
pub(crate) fn new(mut pixels: RgbaImage, format: Format) -> Self {
for pixel in pixels.pixels_mut().filter(|pixel| pixel[3] == 0) {
*pixel = crate::render::TRANSPARENT;
}
Self { pixels, format }
}
#[must_use]
pub fn pixels(&self) -> &RgbaImage {
&self.pixels
}
#[must_use]
pub fn size(&self) -> Size {
Size::new(self.pixels.width(), self.pixels.height())
}
#[must_use]
pub fn format(&self) -> Format {
self.format
}
pub fn to_bytes(&self) -> Result<Vec<u8>, ImageError> {
match self.format {
Format::Jpeg => self.to_jpeg(DEFAULT_JPEG_QUALITY),
Format::Png => {
let mut bytes = Vec::new();
PngEncoder::new(&mut bytes).write_image(
self.pixels.as_raw(),
self.pixels.width(),
self.pixels.height(),
ExtendedColorType::Rgba8,
)?;
Ok(bytes)
}
}
}
pub fn to_jpeg(&self, quality: u8) -> Result<Vec<u8>, ImageError> {
if !(1..=100).contains(&quality) {
return Err(ImageError::InvalidQuality(quality));
}
let rgb: Vec<u8> = self
.pixels
.pixels()
.flat_map(|pixel| {
let [red, green, blue, alpha] = pixel.0;
let alpha = u16::from(alpha);
[red, green, blue].map(|component| {
((u16::from(component) * alpha + 255 * (255 - alpha)) / 255) as u8
})
})
.collect();
let mut bytes = Vec::new();
JpegEncoder::new_with_quality(&mut bytes, quality).encode(
&rgb,
self.pixels.width(),
self.pixels.height(),
ExtendedColorType::Rgb8,
)?;
Ok(bytes)
}
pub fn to_base64(&self) -> Result<String, ImageError> {
Ok(STANDARD.encode(self.to_bytes()?))
}
pub fn to_data_url(&self) -> Result<String, ImageError> {
let data = self.to_base64()?;
Ok(format!("data:{};base64,{data}", self.format.media_type()))
}
pub fn save(&self, path: impl AsRef<Path>) -> Result<(), ImageError> {
let path = path.as_ref();
fs::write(path, self.to_bytes()?).map_err(|source| ImageError::Write {
path: path.to_owned(),
source,
})
}
}