use std::collections::VecDeque;
use fast_image_resize::{FilterType, ResizeAlg, ResizeOptions, Resizer as PixelResizer};
use image::{Rgba, RgbaImage};
use crate::color::Color;
#[cfg(doc)]
use crate::error::ImageError;
use crate::error::{Result, invalid};
use crate::geometry::{Alignment, Dimension, Direction, Resizer, Size};
use crate::image::Image;
use crate::manager::{ImageManager, Source};
fn resample(src: &RgbaImage, crop: Option<(f64, f64, f64, f64)>, width: u32, height: u32) -> RgbaImage {
let full = crop
.is_none_or(|(l, t, w, h)| l == 0.0 && t == 0.0 && w == f64::from(src.width()) && h == f64::from(src.height()));
if full && src.width() == width && src.height() == height {
return src.clone();
}
let mut dst = RgbaImage::new(width.max(1), height.max(1));
let mut options = ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::Bilinear));
if let Some((left, top, w, h)) = crop {
options = options.crop(left, top, w, h);
}
let _ = PixelResizer::new().resize(src, &mut dst, &options);
dst
}
fn blend(dst: &mut RgbaImage, src: &RgbaImage, x: i64, y: i64) {
for (sx, sy, pixel) in src.enumerate_pixels() {
let (dx, dy) = (x + i64::from(sx), y + i64::from(sy));
if dx < 0 || dy < 0 || dx >= i64::from(dst.width()) || dy >= i64::from(dst.height()) {
continue;
}
let target = dst.get_pixel_mut(dx as u32, dy as u32);
*target = over(*pixel, *target);
}
}
fn to_gd_alpha(alpha: u8) -> i32 {
127 - i32::from(alpha >> 1)
}
fn from_gd_alpha(alpha: i32) -> u8 {
(f64::from(127 - alpha) * 255.0 / 127.0).round() as u8
}
fn over(src: Rgba<u8>, dst: Rgba<u8>) -> Rgba<u8> {
let src_alpha = to_gd_alpha(src[3]);
if src_alpha == 0 {
return src;
}
let dst_alpha = to_gd_alpha(dst[3]);
if src_alpha == 127 {
return dst;
}
if dst_alpha == 127 {
return src;
}
let src_weight = 127 - src_alpha;
let dst_weight = (127 - dst_alpha) * src_alpha / 127;
let total = src_weight + dst_weight;
let alpha = src_alpha * dst_alpha / 127;
let channel = |i: usize| ((i32::from(src[i]) * src_weight + i32::from(dst[i]) * dst_weight) / total) as u8;
Rgba([channel(0), channel(1), channel(2), from_gd_alpha(alpha)])
}
fn copy(dst: &mut RgbaImage, src: &RgbaImage, x: i64, y: i64) {
for (sx, sy, pixel) in src.enumerate_pixels() {
let (dx, dy) = (x + i64::from(sx), y + i64::from(sy));
if dx >= 0 && dy >= 0 && dx < i64::from(dst.width()) && dy < i64::from(dst.height()) {
dst.put_pixel(dx as u32, dy as u32, *pixel);
}
}
}
fn clamp_u8(value: f64) -> u8 {
value.clamp(0.0, 255.0) as u8
}
fn map_pixels(buffer: &mut RgbaImage, f: impl Fn([u8; 4]) -> [u8; 4]) {
for pixel in buffer.pixels_mut() {
pixel.0 = f(pixel.0);
}
}
fn convolve(buffer: &RgbaImage, matrix: [[f64; 3]; 3], divisor: f64) -> RgbaImage {
let (width, height) = buffer.dimensions();
let mut out = RgbaImage::new(width, height);
for y in 0..height {
for x in 0..width {
let mut sum = [0.0f64; 3];
for (j, row) in matrix.iter().enumerate() {
let sy = (i64::from(y) - 1 + j as i64).clamp(0, i64::from(height) - 1) as u32;
for (i, weight) in row.iter().enumerate() {
let sx = (i64::from(x) - 1 + i as i64).clamp(0, i64::from(width) - 1) as u32;
let pixel = buffer.get_pixel(sx, sy);
for (c, total) in sum.iter_mut().enumerate() {
*total += f64::from(pixel[c]) * weight;
}
}
}
let alpha = buffer.get_pixel(x, y)[3];
out.put_pixel(
x,
y,
Rgba([
clamp_u8((sum[0] / divisor).round()),
clamp_u8((sum[1] / divisor).round()),
clamp_u8((sum[2] / divisor).round()),
alpha,
]),
);
}
}
out
}
fn rotate_exact(buffer: &RgbaImage, quarter_turns: u32) -> RgbaImage {
match quarter_turns % 4 {
1 => image::imageops::rotate90(buffer),
2 => image::imageops::rotate180(buffer),
3 => image::imageops::rotate270(buffer),
_ => buffer.clone(),
}
}
fn rotate_free(buffer: &RgbaImage, degrees: f64, background: Rgba<u8>) -> RgbaImage {
let (w, h) = (f64::from(buffer.width()), f64::from(buffer.height()));
let radians = degrees.to_radians();
let (sin, cos) = radians.sin_cos();
let new_w = (w * cos.abs() + h * sin.abs()).round().max(1.0) as u32;
let new_h = (w * sin.abs() + h * cos.abs()).round().max(1.0) as u32;
let (cx, cy) = (w / 2.0, h / 2.0);
let (ncx, ncy) = (f64::from(new_w) / 2.0, f64::from(new_h) / 2.0);
let sample = |x: i64, y: i64| -> [f64; 4] {
if x < 0 || y < 0 || x >= i64::from(buffer.width()) || y >= i64::from(buffer.height()) {
background.0.map(f64::from)
} else {
buffer.get_pixel(x as u32, y as u32).0.map(f64::from)
}
};
let mut out = RgbaImage::new(new_w, new_h);
for (x, y, pixel) in out.enumerate_pixels_mut() {
let dx = f64::from(x) + 0.5 - ncx;
let dy = f64::from(y) + 0.5 - ncy;
let sx = dx * cos + dy * sin + cx - 0.5;
let sy = -dx * sin + dy * cos + cy - 0.5;
if sx < -1.0 || sy < -1.0 || sx > w || sy > h {
*pixel = background;
continue;
}
let (x0, y0) = (sx.floor(), sy.floor());
let (fx, fy) = (sx - x0, sy - y0);
let (x0, y0) = (x0 as i64, y0 as i64);
let corners = [
sample(x0, y0),
sample(x0 + 1, y0),
sample(x0, y0 + 1),
sample(x0 + 1, y0 + 1),
];
let mut value = [0u8; 4];
for (c, channel) in value.iter_mut().enumerate() {
let top = corners[0][c] * (1.0 - fx) + corners[1][c] * fx;
let bottom = corners[2][c] * (1.0 - fx) + corners[3][c] * fx;
*channel = clamp_u8((top * (1.0 - fy) + bottom * fy).round());
}
*pixel = Rgba(value);
}
out
}
impl Image {
fn dimensions(&self, width: Dimension, height: Dimension) -> (Option<i64>, Option<i64>) {
(width.resolve(self.width()), height.resolve(self.height()))
}
fn resize_to(&mut self, size: Size) {
let (width, height) = (size.width(), size.height());
self.map_frames(|buffer| resample(buffer, None, width, height));
}
fn background_or(&self, background: Option<&str>) -> Result<Color> {
match background {
Some(color) => Color::parse(color),
None => self.config.background(),
}
}
pub fn resize(&mut self, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Result<&mut Self> {
let (width, height) = self.dimensions(width.into(), height.into());
if width.is_none() && height.is_none() {
return Err(invalid(
"At least one argument must be provided: width, height, or both.",
));
}
let size = Resizer::new(width, height)?.resize(&self.size());
self.resize_to(size);
Ok(self)
}
pub fn resize_down(&mut self, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Result<&mut Self> {
let (width, height) = self.dimensions(width.into(), height.into());
if width.is_none() && height.is_none() {
return Err(invalid(
"At least one argument must be provided: width, height, or both.",
));
}
let size = Resizer::new(width, height)?.resize_down(&self.size());
self.resize_to(size);
Ok(self)
}
pub fn scale(&mut self, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Result<&mut Self> {
let (width, height) = self.dimensions(width.into(), height.into());
if width.is_none() && height.is_none() {
return Err(invalid(
"At least one argument must be provided: width, height, or both.",
));
}
let size = Resizer::new(width, height)?.scale(&self.size());
self.resize_to(size);
Ok(self)
}
pub fn scale_down(&mut self, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Result<&mut Self> {
let (width, height) = self.dimensions(width.into(), height.into());
if width.is_none() && height.is_none() {
return Err(invalid(
"At least one argument must be provided: width, height, or both.",
));
}
let size = Resizer::new(width, height)?.scale_down(&self.size());
self.resize_to(size);
Ok(self)
}
fn cover_with(&mut self, width: Dimension, height: Dimension, alignment: Alignment, down: bool) -> Result<()> {
let (Some(width), Some(height)) = self.dimensions(width, height) else {
return Err(invalid("Width and height are required"));
};
let image_size = self.size();
let mut crop = Resizer::new(Some(image_size.width().into()), Some(image_size.height().into()))?
.contain(&Size::new(width, height)?)?;
crop.align_pivot_to(&image_size, alignment);
let resizer = Resizer::new(Some(width), Some(height))?;
let resize = if down {
resizer.resize_down(&crop)
} else {
resizer.resize(&crop)
};
let rect = (
crop.pivot().x as f64,
crop.pivot().y as f64,
f64::from(crop.width()),
f64::from(crop.height()),
);
let (w, h) = (resize.width(), resize.height());
self.map_frames(|buffer| resample(buffer, Some(rect), w, h));
Ok(())
}
pub fn cover(
&mut self,
width: impl Into<Dimension>,
height: impl Into<Dimension>,
alignment: Alignment,
) -> Result<&mut Self> {
self.cover_with(width.into(), height.into(), alignment, false)?;
Ok(self)
}
pub fn cover_down(
&mut self,
width: impl Into<Dimension>,
height: impl Into<Dimension>,
alignment: Alignment,
) -> Result<&mut Self> {
self.cover_with(width.into(), height.into(), alignment, true)?;
Ok(self)
}
fn contain_with(
&mut self,
width: Dimension,
height: Dimension,
background: Option<&str>,
alignment: Alignment,
down: bool,
) -> Result<()> {
let (Some(width), Some(height)) = self.dimensions(width, height) else {
return Err(invalid("Width and height are required"));
};
let canvas = Size::new(width, height)?;
let resizer = Resizer::new(Some(width), Some(height))?;
let mut crop = if down {
resizer.contain_down(&self.size())?
} else {
resizer.contain(&self.size())?
};
crop.align_pivot_to(&canvas, alignment);
let background = self.background_or(background)?.to_pixel();
let (cw, ch) = (crop.width(), crop.height());
let pivot = crop.pivot();
self.map_frames(|buffer| {
let mut out = RgbaImage::from_pixel(canvas.width(), canvas.height(), background);
copy(&mut out, &resample(buffer, None, cw, ch), pivot.x, pivot.y);
out
});
Ok(())
}
pub fn contain(
&mut self,
width: impl Into<Dimension>,
height: impl Into<Dimension>,
background: Option<&str>,
alignment: Alignment,
) -> Result<&mut Self> {
self.contain_with(width.into(), height.into(), background, alignment, false)?;
Ok(self)
}
pub fn contain_down(
&mut self,
width: impl Into<Dimension>,
height: impl Into<Dimension>,
background: Option<&str>,
alignment: Alignment,
) -> Result<&mut Self> {
self.contain_with(width.into(), height.into(), background, alignment, true)?;
Ok(self)
}
pub fn crop(
&mut self,
width: impl Into<Dimension>,
height: impl Into<Dimension>,
x: i64,
y: i64,
background: Option<&str>,
alignment: Alignment,
) -> Result<&mut Self> {
let (Some(width), Some(height)) = self.dimensions(width.into(), height.into()) else {
return Err(invalid("Width and height are required"));
};
let mut crop = Size::new(width, height)?;
crop.move_pivot(alignment, 0, 0);
crop.align_pivot_to(&self.size(), alignment);
let background = self.background_or(background)?.to_pixel();
self.crop_frames(
crop.width(),
crop.height(),
crop.pivot().x + x,
crop.pivot().y + y,
background,
);
Ok(self)
}
fn crop_frames(&mut self, width: u32, height: u32, offset_x: i64, offset_y: i64, background: Rgba<u8>) {
self.map_frames(|buffer| {
let mut out = RgbaImage::from_pixel(width.max(1), height.max(1), background);
copy(&mut out, buffer, -offset_x, -offset_y);
out
});
}
fn resize_canvas_with(
&mut self,
width: Dimension,
height: Dimension,
background: Option<&str>,
alignment: Alignment,
relative: bool,
) -> Result<()> {
let (width, height) = self.dimensions(width, height);
let (current_w, current_h) = (i64::from(self.width()), i64::from(self.height()));
let (w, h) = if relative {
(
width.map_or(current_w, |w| current_w + w),
height.map_or(current_h, |h| current_h + h),
)
} else {
(width.unwrap_or(current_w), height.unwrap_or(current_h))
};
let mut size = Size::new(w, h)?;
size.align_pivot_to(&self.size(), alignment);
let background = self.background_or(background)?.to_pixel();
self.crop_frames(size.width(), size.height(), size.pivot().x, size.pivot().y, background);
Ok(())
}
pub fn resize_canvas(
&mut self,
width: impl Into<Dimension>,
height: impl Into<Dimension>,
background: Option<&str>,
alignment: Alignment,
) -> Result<&mut Self> {
self.resize_canvas_with(width.into(), height.into(), background, alignment, false)?;
Ok(self)
}
pub fn resize_canvas_relative(
&mut self,
width: impl Into<Dimension>,
height: impl Into<Dimension>,
background: Option<&str>,
alignment: Alignment,
) -> Result<&mut Self> {
self.resize_canvas_with(width.into(), height.into(), background, alignment, true)?;
Ok(self)
}
pub fn rotate(&mut self, angle: f64, background: Option<&str>) -> Result<&mut Self> {
let background = self.background_or(background)?.to_pixel();
let angle = angle % 360.0;
let normalized = if angle < 0.0 { angle + 360.0 } else { angle };
if normalized % 90.0 == 0.0 {
let turns = (normalized / 90.0) as u32;
self.map_frames(|buffer| rotate_exact(buffer, turns));
} else {
self.map_frames(|buffer| rotate_free(buffer, normalized, background));
}
Ok(self)
}
pub fn orient(&mut self) -> &mut Self {
let orientation = self.exif.orientation().unwrap_or(0);
match orientation {
2 => self.flip(Direction::Horizontal),
3 => self.rotate_quarters(2),
4 => self.rotate_quarters(2).flip(Direction::Horizontal),
5 => self.rotate_quarters(1).flip(Direction::Horizontal),
6 => self.rotate_quarters(1),
7 => self.rotate_quarters(3).flip(Direction::Horizontal),
8 => self.rotate_quarters(3),
_ => self,
};
self.exif.set_orientation(1);
self
}
fn rotate_quarters(&mut self, turns: u32) -> &mut Self {
self.map_frames(|buffer| rotate_exact(buffer, turns));
self
}
pub fn flip(&mut self, direction: Direction) -> &mut Self {
self.each_frame(|buffer| match direction {
Direction::Horizontal => image::imageops::flip_horizontal_in_place(buffer),
Direction::Vertical => image::imageops::flip_vertical_in_place(buffer),
});
self
}
pub fn grayscale(&mut self) -> &mut Self {
self.each_frame(|buffer| {
map_pixels(buffer, |[r, g, b, a]| {
let gray = (0.299 * f64::from(r) + 0.587 * f64::from(g) + 0.114 * f64::from(b)) as u8;
[gray, gray, gray, a]
});
});
self
}
pub fn invert(&mut self) -> &mut Self {
self.each_frame(|buffer| map_pixels(buffer, |[r, g, b, a]| [255 - r, 255 - g, 255 - b, a]));
self
}
pub fn brightness(&mut self, level: i32) -> &mut Self {
let amount = ((f64::from(level) * 2.55) as i64).clamp(-255, 255) as f64;
self.each_frame(|buffer| {
map_pixels(buffer, |[r, g, b, a]| {
let adjust = |c: u8| clamp_u8(f64::from(c) + amount);
[adjust(r), adjust(g), adjust(b), a]
});
});
self
}
pub fn contrast(&mut self, level: i32) -> &mut Self {
let factor = ((100.0 + f64::from(level)) / 100.0).powi(2);
self.each_frame(|buffer| {
map_pixels(buffer, |[r, g, b, a]| {
let adjust = |c: u8| clamp_u8(((f64::from(c) / 255.0 - 0.5) * factor + 0.5) * 255.0);
[adjust(r), adjust(g), adjust(b), a]
});
});
self
}
pub fn gamma(&mut self, gamma: f64) -> &mut Self {
let exponent = 1.0 / gamma;
self.each_frame(|buffer| {
map_pixels(buffer, |[r, g, b, a]| {
let adjust = |c: u8| clamp_u8((f64::from(c) / 255.0).powf(exponent) * 255.0 + 0.5);
[adjust(r), adjust(g), adjust(b), a]
});
});
self
}
pub fn colorize(&mut self, red: i32, green: i32, blue: i32) -> Result<&mut Self> {
for (name, level) in [("red", red), ("green", green), ("blue", blue)] {
if !(-100..=100).contains(&level) {
return Err(invalid(format!(
"Color level for argument ${name} must be in range -100 to 100"
)));
}
}
let scale = |level: i32| (f64::from(level) * 2.55).round();
let (dr, dg, db) = (scale(red), scale(green), scale(blue));
self.each_frame(|buffer| {
map_pixels(buffer, |[r, g, b, a]| {
[
clamp_u8(f64::from(r) + dr),
clamp_u8(f64::from(g) + dg),
clamp_u8(f64::from(b) + db),
a,
]
});
});
Ok(self)
}
pub fn blur(&mut self, level: u32) -> &mut Self {
let kernel = [[1.0, 2.0, 1.0], [2.0, 4.0, 2.0], [1.0, 2.0, 1.0]];
self.each_frame(|buffer| {
for _ in 0..level {
*buffer = convolve(buffer, kernel, 16.0);
}
});
self
}
pub fn sharpen(&mut self, level: u32) -> &mut Self {
let level = f64::from(level);
let min = if level >= 10.0 { level * -0.01 } else { 0.0 };
let max = level * -0.025;
let abs = -(4.0 * min + 4.0 * max) + 1.0;
let matrix = [[min, max, min], [max, abs, max], [min, max, min]];
self.each_frame(|buffer| *buffer = convolve(buffer, matrix, 1.0));
self
}
pub fn pixelate(&mut self, size: u32) -> Result<&mut Self> {
if size < 1 {
return Err(invalid("Invalid pixelation size. Must be int<1, max>"));
}
self.each_frame(|buffer| {
let (width, height) = buffer.dimensions();
for by in (0..height).step_by(size as usize) {
for bx in (0..width).step_by(size as usize) {
let (ex, ey) = ((bx + size).min(width), (by + size).min(height));
let mut sum = [0u64; 4];
for y in by..ey {
for x in bx..ex {
for (total, value) in sum.iter_mut().zip(buffer.get_pixel(x, y).0) {
*total += u64::from(value);
}
}
}
let count = u64::from((ex - bx) * (ey - by));
let average = Rgba(sum.map(|total| (total / count) as u8));
for y in by..ey {
for x in bx..ex {
buffer.put_pixel(x, y, average);
}
}
}
}
});
Ok(self)
}
pub fn insert(
&mut self,
source: impl Into<Source>,
x: i64,
y: i64,
alignment: Alignment,
transparency: f64,
) -> Result<&mut Self> {
if !(0.0..=1.0).contains(&transparency) {
return Err(invalid("Transparency must be in range 0 to 1"));
}
let watermark = ImageManager::new(self.config.clone()).decode(source)?;
let mut mark = watermark.first().clone();
if transparency < 1.0 {
map_pixels(&mut mark, |[r, g, b, a]| {
let alpha = 127 - (f64::from(127 - to_gd_alpha(a)) * transparency).round() as i32;
[r, g, b, from_gd_alpha(alpha)]
});
}
let mut image_size = self.size();
image_size.move_pivot(alignment, x, y);
let mut mark_size = watermark.size();
mark_size.move_pivot(alignment, 0, 0);
let position = image_size.offset_to(&mark_size);
self.each_frame(|buffer| blend(buffer, &mark, position.x, position.y));
Ok(self)
}
pub fn fill(&mut self, color: &str, x: Option<u32>, y: Option<u32>) -> Result<&mut Self> {
let color = Color::parse(color)?.to_pixel();
match (x, y) {
(Some(x), Some(y)) => self.each_frame(|buffer| flood_fill(buffer, x, y, color)),
_ => self.each_frame(|buffer| {
for pixel in buffer.pixels_mut() {
*pixel = over(color, *pixel);
}
}),
}
Ok(self)
}
}
fn flood_fill(buffer: &mut RgbaImage, x: u32, y: u32, color: Rgba<u8>) {
if x >= buffer.width() || y >= buffer.height() {
return;
}
let target = *buffer.get_pixel(x, y);
if target == color {
return;
}
let mut queue = VecDeque::from([(x, y)]);
while let Some((x, y)) = queue.pop_front() {
if *buffer.get_pixel(x, y) != target {
continue;
}
buffer.put_pixel(x, y, color);
if x > 0 {
queue.push_back((x - 1, y));
}
if y > 0 {
queue.push_back((x, y - 1));
}
if x + 1 < buffer.width() {
queue.push_back((x + 1, y));
}
if y + 1 < buffer.height() {
queue.push_back((x, y + 1));
}
}
}