laravel-image 0.2.0

Image handling and manipulation for Laravel Rust, in pure Rust: a port of intervention/image-laravel and Intervention Image.
Documentation
//! RGB colors and the color strings Intervention Image decodes.

use std::fmt;
use std::str::FromStr;

use crate::error::{ImageError, Result};

/// An RGBA color: Intervention Image's `Colors\Rgb\Color`, with 8-bit channels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Color {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
    /// `255` is opaque, `0` fully transparent.
    pub alpha: u8,
}

impl Color {
    pub const fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
        Self {
            red,
            green,
            blue,
            alpha,
        }
    }

    pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
        Self::rgba(red, green, blue, 255)
    }

    /// `transparent`: white with no opacity, as PHP decodes it.
    pub const TRANSPARENT: Color = Color::rgba(255, 255, 255, 0);

    /// Decode a color string: hex (`f50`, `#ff5500`, `ff550080`), `rgb(255, 85, 0)`,
    /// `rgba(255, 85, 0, 0.5)` or `transparent`.
    ///
    /// # Errors
    ///
    /// [`ImageError::ColorDecoder`] for any other string, including the named colors and the
    /// CMYK, HSL, HSV, OKLab and OKLCH notations, which this release doesn't decode yet.
    pub fn parse(input: &str) -> Result<Color> {
        let value = input.trim().to_lowercase();
        if value == "transparent" {
            return Ok(Color::TRANSPARENT);
        }
        if let Some(color) = parse_hex(&value) {
            return Ok(color);
        }
        if let Some(color) = parse_rgb(&value) {
            return Ok(color);
        }
        Err(ImageError::ColorDecoder(format!(
            "Unable to decode color from \"{input}\""
        )))
    }

    /// The color as hex without `#`: `ff5500`, or `ff550080` when not opaque.
    pub fn to_hex(&self) -> String {
        if self.alpha == 255 {
            format!("{:02x}{:02x}{:02x}", self.red, self.green, self.blue)
        } else {
            format!("{:02x}{:02x}{:02x}{:02x}", self.red, self.green, self.blue, self.alpha)
        }
    }

    /// Fully transparent.
    pub fn is_clear(&self) -> bool {
        self.alpha == 0
    }

    /// Fully opaque.
    pub fn is_opaque(&self) -> bool {
        self.alpha == 255
    }

    pub(crate) fn to_pixel(self) -> image::Rgba<u8> {
        image::Rgba([self.red, self.green, self.blue, self.alpha])
    }

    pub(crate) fn from_pixel(pixel: image::Rgba<u8>) -> Color {
        let [red, green, blue, alpha] = pixel.0;
        Color {
            red,
            green,
            blue,
            alpha,
        }
    }
}

impl FromStr for Color {
    type Err = ImageError;

    fn from_str(input: &str) -> Result<Self> {
        Color::parse(input)
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.to_hex())
    }
}

fn parse_hex(value: &str) -> Option<Color> {
    let hex = value.strip_prefix('#').unwrap_or(value);
    if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
        return None;
    }
    let channel = |part: &str| -> Option<u8> {
        match part.len() {
            1 => u8::from_str_radix(&part.repeat(2), 16).ok(),
            _ => u8::from_str_radix(part, 16).ok(),
        }
    };
    let parts: Vec<&str> = match hex.len() {
        3 | 4 => (0..hex.len()).map(|i| &hex[i..=i]).collect(),
        6 | 8 => (0..hex.len()).step_by(2).map(|i| &hex[i..i + 2]).collect(),
        _ => return None,
    };
    let values: Option<Vec<u8>> = parts.into_iter().map(channel).collect();
    let values = values?;
    Some(Color::rgba(
        values[0],
        values[1],
        values[2],
        values.get(3).copied().unwrap_or(255),
    ))
}

fn parse_rgb(value: &str) -> Option<Color> {
    let inner = value
        .strip_prefix("rgba(")
        .or_else(|| value.strip_prefix("rgb("))?
        .strip_suffix(')')?;
    let (channels, alpha) = match inner.split_once('/') {
        Some((channels, alpha)) => (channels, Some(alpha)),
        None => (inner, None),
    };
    let mut parts: Vec<&str> = channels
        .split(|c: char| c == ',' || c.is_whitespace())
        .filter(|part| !part.is_empty())
        .collect();
    let alpha = match alpha {
        Some(alpha) => Some(alpha.trim()),
        None if parts.len() == 4 => parts.pop(),
        None => None,
    };
    if parts.len() != 3 {
        return None;
    }
    let channel = |part: &str| -> Option<u8> {
        if let Some(percent) = part.strip_suffix('%') {
            let percent: f64 = percent.parse().ok()?;
            return (0.0..=100.0).contains(&percent).then(|| (percent * 2.55).round() as u8);
        }
        let value: f64 = part.parse().ok()?;
        (0.0..=255.0).contains(&value).then(|| value.round() as u8)
    };
    let alpha = match alpha {
        None => 255,
        Some(alpha) => {
            let normalized = match alpha.strip_suffix('%') {
                Some(percent) => percent.parse::<f64>().ok()? / 100.0,
                None => alpha.parse::<f64>().ok()?,
            };
            if !(0.0..=1.0).contains(&normalized) {
                return None;
            }
            (normalized * 255.0).round() as u8
        }
    };
    Some(Color::rgba(
        channel(parts[0])?,
        channel(parts[1])?,
        channel(parts[2])?,
        alpha,
    ))
}

#[cfg(test)]
mod tests {
    use super::Color;

    #[test]
    fn decodes_hex_rgb_and_transparent() {
        assert_eq!(Color::parse("f50").unwrap(), Color::rgb(255, 85, 0));
        assert_eq!(Color::parse("#FF5500").unwrap(), Color::rgb(255, 85, 0));
        assert_eq!(Color::parse("ff550080").unwrap(), Color::rgba(255, 85, 0, 128));
        assert_eq!(Color::parse("#f508").unwrap(), Color::rgba(255, 85, 0, 136));
        assert_eq!(Color::parse("rgb(255, 85, 0)").unwrap(), Color::rgb(255, 85, 0));
        assert_eq!(
            Color::parse("rgba(255, 85, 0, 0.5)").unwrap(),
            Color::rgba(255, 85, 0, 128)
        );
        assert_eq!(Color::parse("transparent").unwrap(), Color::TRANSPARENT);
        assert!(Color::parse("ffff").is_ok());
        assert!(Color::parse("fffff").is_err());
        assert!(Color::parse("rgb(300, 0, 0)").is_err());
        assert_eq!(Color::rgb(255, 85, 0).to_hex(), "ff5500");
    }
}