caprs 0.1.1

Image-based click, slide, drag and rotate CAPTCHA generation and verification
Documentation
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;

/// The default encoding of a generated image.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Format {
    /// JPEG with no transparency.
    Jpeg,
    /// PNG with an alpha channel.
    Png,
}

impl Format {
    /// Returns the MIME media type used in HTTP and data URLs.
    #[must_use]
    pub const fn media_type(self) -> &'static str {
        match self {
            Self::Jpeg => "image/jpeg",
            Self::Png => "image/png",
        }
    }
}

/// Failure while encoding or saving a generated image.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ImageError {
    /// JPEG quality was outside the accepted range of 1 through 100.
    #[error("JPEG quality must be in 1..=100, got {0}")]
    InvalidQuality(u8),
    /// The image encoder rejected the data.
    #[error("could not encode image")]
    Encode(#[from] image::ImageError),
    /// Writing the encoded image to disk failed.
    #[error("could not write image to {path}", path = .path.display())]
    Write {
        /// Destination path of the attempted write.
        path: std::path::PathBuf,
        /// Underlying filesystem error.
        #[source]
        source: io::Error,
    },
}

/// A generated image with a default encoding and access to the uncompressed pixels.
#[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 {
        // PNG stores RGB even at zero alpha. Remove source pixels outside the cutout.
        for pixel in pixels.pixels_mut().filter(|pixel| pixel[3] == 0) {
            *pixel = crate::render::TRANSPARENT;
        }
        Self { pixels, format }
    }

    /// Borrows the original RGBA pixels for custom image processing or encoding.
    #[must_use]
    pub fn pixels(&self) -> &RgbaImage {
        &self.pixels
    }

    /// Returns the dimensions of the generated image in pixels.
    #[must_use]
    pub fn size(&self) -> Size {
        Size::new(self.pixels.width(), self.pixels.height())
    }

    /// Reports the encoding used by the default export methods.
    #[must_use]
    pub fn format(&self) -> Format {
        self.format
    }

    /// Encodes the image using its default format. JPEG uses quality 100.
    ///
    /// # Errors
    ///
    /// Returns an error if encoding fails.
    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)
            }
        }
    }

    /// Encodes the pixels as JPEG, compositing transparency over white.
    ///
    /// # Errors
    ///
    /// Returns an error if quality is outside 1 through 100 or encoding fails.
    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)
    }

    /// Returns the standard Base64 representation of the encoded image.
    ///
    /// # Errors
    ///
    /// Returns an error if encoding fails.
    pub fn to_base64(&self) -> Result<String, ImageError> {
        Ok(STANDARD.encode(self.to_bytes()?))
    }

    /// Returns a data URL with the media type and Base64 data for this image.
    ///
    /// # Errors
    ///
    /// Returns an error if encoding fails.
    pub fn to_data_url(&self) -> Result<String, ImageError> {
        let data = self.to_base64()?;
        Ok(format!("data:{};base64,{data}", self.format.media_type()))
    }

    /// Saves the image in its default format, using the path as given.
    ///
    /// # Errors
    ///
    /// Returns an error if encoding or writing the file fails.
    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,
        })
    }
}