Dezio/src/pix.rs
astar76 bc8992673c Dezio: an all-in-one Discord bot in Rust
Music with a live player, Last.fm, video downloads, games, AI chat, moderation, logging,
a web dashboard and a Game Boy Activity.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 11:47:43 -05:00

186 lines
6 KiB
Rust

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Small pixel helpers shared by quotes and image effects (the `image` crate has no PIL-style enhancers).
use image::imageops::{self, FilterType};
use image::{GrayImage, Luma, Rgba, RgbaImage};
pub fn decode(bytes: &[u8]) -> Option<RgbaImage> {
image::load_from_memory(bytes).ok().map(|d| d.to_rgba8())
}
pub fn encode_png(img: &RgbaImage) -> Vec<u8> {
let mut out = std::io::Cursor::new(Vec::new());
let _ = img.write_to(&mut out, image::ImageFormat::Png);
out.into_inner()
}
pub fn hex(text: &str, default: [u8; 3]) -> [u8; 3] {
let t = text.trim().trim_start_matches('#');
if t.len() == 6 {
if let Ok(v) = u32::from_str_radix(t, 16) {
return [(v >> 16) as u8, (v >> 8) as u8, v as u8];
}
}
default
}
pub fn to_hex(c: [u8; 3]) -> String {
format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
}
/// Scale to cover `w`×`h`, then crop the middle (like PIL's `ImageOps.fit`).
pub fn cover(img: &RgbaImage, w: u32, h: u32) -> RgbaImage {
let scale = (w as f32 / img.width() as f32).max(h as f32 / img.height() as f32);
let (sw, sh) = (((img.width() as f32 * scale).round() as u32).max(w), ((img.height() as f32 * scale).round() as u32).max(h));
let big = imageops::resize(img, sw, sh, FilterType::Lanczos3);
imageops::crop_imm(&big, (sw - w) / 2, (sh - h) / 2, w, h).to_image()
}
/// Scale down so neither side is longer than `limit` (never up).
pub fn thumbnail(img: &RgbaImage, limit: u32) -> RgbaImage {
if img.width() <= limit && img.height() <= limit {
return img.clone();
}
let scale = limit as f32 / img.width().max(img.height()) as f32;
imageops::resize(img, ((img.width() as f32 * scale).round() as u32).max(1), ((img.height() as f32 * scale).round() as u32).max(1), FilterType::Triangle)
}
fn luma(p: &Rgba<u8>) -> f32 {
0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32
}
pub fn grayscale(img: &mut RgbaImage) {
for p in img.pixels_mut() {
let l = luma(p).round() as u8;
p[0] = l;
p[1] = l;
p[2] = l;
}
}
/// PIL `ImageEnhance.Contrast`: push colours away from the average brightness.
pub fn contrast(img: &mut RgbaImage, factor: f32) {
let n = (img.width() * img.height()).max(1) as f32;
let mean = img.pixels().map(luma).sum::<f32>() / n;
for p in img.pixels_mut() {
for c in 0..3 {
p[c] = (mean + (p[c] as f32 - mean) * factor).clamp(0.0, 255.0).round() as u8;
}
}
}
/// PIL `ImageEnhance.Color`: 0 = grey, 1 = unchanged, >1 = more vivid.
pub fn saturate(img: &mut RgbaImage, factor: f32) {
for p in img.pixels_mut() {
let l = luma(p);
for c in 0..3 {
p[c] = (l + (p[c] as f32 - l) * factor).clamp(0.0, 255.0).round() as u8;
}
}
}
/// PIL `ImageEnhance.Sharpness`: blend between a blurred copy and the original.
pub fn sharpen(img: &mut RgbaImage, factor: f32) {
let blurred = imageops::blur(img, 1.0);
for (p, b) in img.pixels_mut().zip(blurred.pixels()) {
for c in 0..3 {
p[c] = (b[c] as f32 + (p[c] as f32 - b[c] as f32) * factor).clamp(0.0, 255.0).round() as u8;
}
}
}
/// Multiply each colour channel (a 3×3 matrix, like PIL's `convert("RGB", matrix)`).
pub fn matrix(img: &mut RgbaImage, m: [[f32; 3]; 3]) {
for p in img.pixels_mut() {
let (r, g, b) = (p[0] as f32, p[1] as f32, p[2] as f32);
for c in 0..3 {
p[c] = (m[c][0] * r + m[c][1] * g + m[c][2] * b).clamp(0.0, 255.0).round() as u8;
}
}
}
pub fn posterize(img: &mut RgbaImage, bits: u32) {
let mask = !((1u16 << (8 - bits)) - 1) as u8;
for p in img.pixels_mut() {
for c in 0..3 {
p[c] &= mask;
}
}
}
/// Scale every pixel's alpha by `f(x, y)` (0..1).
pub fn fade_alpha(img: &mut RgbaImage, f: impl Fn(u32, u32) -> f32) {
let (w, h) = img.dimensions();
for y in 0..h {
for x in 0..w {
let p = img.get_pixel_mut(x, y);
p[3] = (p[3] as f32 * f(x, y).clamp(0.0, 1.0)).round() as u8;
}
}
}
/// Soft-edged circle crop (the corners become transparent).
pub fn circle(img: &mut RgbaImage) {
let (w, h) = img.dimensions();
let (cx, cy, r) = (w as f32 / 2.0, h as f32 / 2.0, w.min(h) as f32 / 2.0);
fade_alpha(img, |x, y| {
let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
(r - d + 0.5).clamp(0.0, 1.0)
});
}
pub fn smoothstep(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// A blurred mask like PIL's `GaussianBlur` on an `L` image.
pub fn blur_mask(mask: &GrayImage, sigma: f32) -> GrayImage {
imageops::blur(mask, sigma)
}
pub fn gray(v: u8) -> Luma<u8> {
Luma([v])
}
pub fn paste(dst: &mut RgbaImage, src: &RgbaImage, x: i64, y: i64) {
imageops::overlay(dst, src, x, y);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn colours_round_trip() {
assert_eq!(hex("#FF8800", [0; 3]), [255, 136, 0]);
assert_eq!(hex("nope", [1, 2, 3]), [1, 2, 3]);
assert_eq!(to_hex([255, 136, 0]), "#ff8800");
}
#[test]
fn cover_crops_the_middle() {
let img = RgbaImage::from_pixel(100, 50, Rgba([9, 9, 9, 255]));
let out = cover(&img, 40, 40);
assert_eq!(out.dimensions(), (40, 40));
}
#[test]
fn circle_clears_corners() {
let mut img = RgbaImage::from_pixel(20, 20, Rgba([255, 0, 0, 255]));
circle(&mut img);
assert_eq!(img.get_pixel(0, 0)[3], 0);
assert_eq!(img.get_pixel(10, 10)[3], 255);
}
}
/// A filled rounded rectangle.
pub fn rounded_rect(img: &mut RgbaImage, x: i32, y: i32, w: i32, h: i32, r: i32, c: Rgba<u8>) {
for py in y.max(0)..(y + h).min(img.height() as i32) {
for px in x.max(0)..(x + w).min(img.width() as i32) {
let (dx, dy) = ((px - x).min(x + w - 1 - px), (py - y).min(y + h - 1 - py));
let inside = if dx >= r || dy >= r { true } else { (r - dx - 1).pow(2) + (r - dy - 1).pow(2) <= r * r };
if inside {
img.put_pixel(px as u32, py as u32, c);
}
}
}
}