versatiles_image 4.6.1

A toolbox for converting, checking and serving map tiles in various formats.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! High-level image operations for `DynamicImage` used in VersaTiles.
//!
//! This module provides [`DynamicImageTraitOperation`], which augments `image::DynamicImage` with
//! pragmatic helpers for common tile-processing tasks:
//!
//! - Removing alpha channels (unconditionally or only if fully opaque)
//! - Computing a quick representative/average color
//! - Cropping with resampling and downscaling with configurable filters
//! - Alpha-aware flattening against a background color
//! - In-place mutation of color channels (leaving alpha intact)
//! - In-place overlay compositing of two images with size validation
//!
//! Most operations use efficient backends (`fast_image_resize` where applicable) and avoid
//! unnecessary allocations.

use super::info::DynamicImageTraitInfo;
use anyhow::{Result, bail};
use fast_image_resize::{FilterType, ResizeAlg, ResizeOptions, Resizer};
use image::{DynamicImage, Rgb, imageops::overlay};
use imageproc::map::map_pixels;
use versatiles_derive::context;

/// High-level convenience operations for modifying and transforming `DynamicImage`s.
pub trait DynamicImageTraitOperation: DynamicImageTraitInfo {
	/// Returns a copy of the image **without** an alpha channel.
	///
	/// * `Rgba8` → `Rgb8`, `La8` → `L8`. Non‑alpha images are returned unchanged.
	/// * Returns an error for unsupported color types.
	fn to_no_alpha(&self) -> Result<DynamicImage>;

	/// Computes a quick **representative color** of the image.
	///
	/// This downsamples to 1×1 using a triangle filter and returns the resulting pixel bytes
	/// (3 or 4 channels depending on the source color type).
	fn average_color(&self) -> Vec<u8>;

	/// Crops the source region `(x, y, w, h)` and resamples it into a destination image of
	/// size `width_dst × height_dst` using `fast_image_resize`.
	///
	/// Coordinates are given in source pixel space. Returns an error on resize failures.
	fn extract(&self, x: f64, y: f64, w: f64, h: f64, width_dst: u32, height_dst: u32) -> Result<DynamicImage>;

	/// Produces a scaled‑down copy by the integer `factor` using a **box filter**.
	///
	/// Panics if `factor == 0`. Returns an error on resize failures.
	fn scaled_down(&self, factor: u32) -> Result<DynamicImage>;

	/// Flattens an image with alpha against a given **background color**.
	///
	/// For `Rgba8`: returns an `Rgb8` where each pixel is `alpha * src + (1-alpha) * bg`.
	/// Non‑alpha images are returned unchanged. Errors on unsupported color types.
	fn into_flattened(self, color: Rgb<u8>) -> Result<DynamicImage>;

	/// Converts the image to a non‑alpha variant **only if it is fully opaque**.
	///
	/// For non‑alpha images this is a no‑op. Errors for unsupported color types.
	fn into_no_alpha_if_opaque(self) -> Result<DynamicImage>;

	/// Unconditionally removes the alpha channel (if present) and returns the result.
	///
	/// Non‑alpha images are returned unchanged. Errors for unsupported color types.
	fn into_no_alpha(self) -> Result<DynamicImage>;

	/// Like [`scaled_down`](Self::scaled_down), but consumes `self` and returns the result.
	///
	/// Returns `self` unchanged when `factor == 1`.
	fn into_scaled_down(self, factor: u32) -> Result<DynamicImage>;

	/// Sets **all alpha values to 255** in place, making the image fully opaque.
	///
	/// Has no effect on images without alpha. Errors on unsupported color types.
	fn make_opaque(&mut self) -> Result<()>;

	/// Applies a mapping function `f` to **color channels only**, leaving the alpha channel intact.
	///
	/// The function is called per component (`u8`). Errors on unsupported color types.
	fn map_color_values<F>(&mut self, f: F)
	where
		F: Fn(u8) -> u8;

	/// Draws `top` over `self` in place (composites at (0,0)).
	///
	/// Ensures the images have identical dimensions. Returns an error if sizes differ.
	fn overlay(&mut self, top: &DynamicImage) -> Result<()>;

	/// Composite `top` onto `self` using additive alpha blending.
	///
	/// Assumes translucent pixels represent non-overlapping spatial coverage (e.g. orthoimagery edges).
	/// ```text
	/// alpha_out = min(1.0, alpha_A + alpha_B)
	/// color_out = (color_A * alpha_A + color_B * alpha_B) / alpha_out
	/// ```
	/// Ensures the images have identical dimensions. Returns an error if sizes differ.
	fn overlay_additive(&mut self, top: &DynamicImage) -> Result<()>;
}

impl DynamicImageTraitOperation for DynamicImage
where
	DynamicImage: DynamicImageTraitInfo,
{
	#[context("removing alpha from {:?} image (has_alpha={})", self.color(), self.has_alpha())]
	fn to_no_alpha(&self) -> Result<DynamicImage> {
		Ok(match self {
			DynamicImage::ImageRgba8(_) => DynamicImage::from(self.to_rgb8()),
			DynamicImage::ImageLumaA8(_) => DynamicImage::from(self.to_luma8()),
			DynamicImage::ImageRgb8(_) | DynamicImage::ImageLuma8(_) => self.clone(),
			_ => bail!("Unsupported image type for removing alpha: {:?}", self.color()),
		})
	}

	fn average_color(&self) -> Vec<u8> {
		let img = self.resize_exact(1, 1, image::imageops::FilterType::Triangle);
		img.into_bytes()
	}

	#[context("extracting region ({:.2},{:.2},{:.2},{:.2}) from {}x{} into {}x{}", x, y, w, h, self.width(), self.height(), width_dst, height_dst)]
	fn extract(&self, x: f64, y: f64, w: f64, h: f64, width_dst: u32, height_dst: u32) -> Result<DynamicImage> {
		let mut dst_image = DynamicImage::new(width_dst, height_dst, self.color());
		Resizer::new().resize(self, &mut dst_image, &ResizeOptions::default().crop(x, y, w, h))?;
		Ok(dst_image)
	}

	#[context("downscaling {}x{} by factor {} ({:?})", self.width(), self.height(), factor, self.color())]
	fn scaled_down(&self, factor: u32) -> Result<DynamicImage> {
		assert!(factor > 0, "Scaling factor must be greater than zero");

		let mut dst_image = DynamicImage::new(self.width() / factor, self.height() / factor, self.color());
		Resizer::new().resize(
			self,
			&mut dst_image,
			&ResizeOptions::default().resize_alg(ResizeAlg::Convolution(FilterType::Box)),
		)?;

		Ok(dst_image)
	}

	#[context("flattening image onto RGB({:?})", color)]
	#[allow(clippy::cast_possible_truncation)]
	fn into_flattened(self, color: Rgb<u8>) -> Result<DynamicImage> {
		if !self.has_alpha() {
			return Ok(self);
		}
		match self {
			DynamicImage::ImageRgba8(img) => {
				let c = [u16::from(color[0]), u16::from(color[1]), u16::from(color[2])];
				Ok(DynamicImage::from(map_pixels(&img, |p| {
					if p[3] == 255 {
						Rgb([p[0], p[1], p[2]])
					} else {
						let a = u16::from(p[3]);
						let b = u16::from(255 - p[3]);
						Rgb([
							(((u16::from(p[0]) * a) + c[0] * b + 127) / 255) as u8,
							(((u16::from(p[1]) * a) + c[1] * b + 127) / 255) as u8,
							(((u16::from(p[2]) * a) + c[2] * b + 127) / 255) as u8,
						])
					}
				})))
			}
			_ => bail!("Unsupported image type {:?} for flattening", self.color()),
		}
	}

	#[context("dropping alpha from image")]
	fn into_no_alpha(self) -> Result<DynamicImage> {
		Ok(match self {
			DynamicImage::ImageRgba8(_) => DynamicImage::from(self.into_rgb8()),
			DynamicImage::ImageLumaA8(_) => DynamicImage::from(self.into_luma8()),
			DynamicImage::ImageRgb8(_) | DynamicImage::ImageLuma8(_) => self,
			_ => bail!("Unsupported image type for removing alpha: {:?}", self.color()),
		})
	}

	#[context("removing alpha if opaque")]
	fn into_no_alpha_if_opaque(self) -> Result<DynamicImage> {
		if self.has_alpha() && self.is_opaque() {
			self.into_no_alpha()
		} else {
			Ok(self)
		}
	}

	#[context("downscaling image by factor {factor}")]
	fn into_scaled_down(self, factor: u32) -> Result<DynamicImage> {
		if factor == 1 {
			Ok(self)
		} else {
			self.scaled_down(factor)
		}
	}

	#[context("forcing opacity for {:?} image", self.color())]
	fn make_opaque(&mut self) -> Result<()> {
		match *self {
			DynamicImage::ImageRgba8(ref mut img) => {
				for p in img.pixels_mut() {
					p[3] = 255;
				}
			}
			DynamicImage::ImageLumaA8(ref mut img) => {
				for p in img.pixels_mut() {
					p[1] = 255;
				}
			}
			DynamicImage::ImageRgb8(_) | DynamicImage::ImageLuma8(_) => {}
			_ => bail!("Unsupported image type for removing alpha: {:?}", self.color()),
		}
		Ok(())
	}

	fn map_color_values<F>(&mut self, f: F)
	where
		F: Fn(u8) -> u8,
	{
		match self {
			DynamicImage::ImageLuma8(img) => {
				for p in img.pixels_mut() {
					p[0] = f(p[0]);
				}
			}
			DynamicImage::ImageLumaA8(img) => {
				for p in img.pixels_mut() {
					p[0] = f(p[0]);
				}
			}
			DynamicImage::ImageRgb8(img) => {
				for p in img.pixels_mut() {
					p[0] = f(p[0]);
					p[1] = f(p[1]);
					p[2] = f(p[2]);
				}
			}
			DynamicImage::ImageRgba8(img) => {
				for p in img.pixels_mut() {
					p[0] = f(p[0]);
					p[1] = f(p[1]);
					p[2] = f(p[2]);
				}
			}
			_ => panic!("Unsupported image type for mutating color values: {:?}", self.color()),
		}
	}

	#[context("overlaying top {}x{} {:?} onto base {}x{} {:?}", top.width(), top.height(), top.color(), self.width(), self.height(), self.color())]
	fn overlay(&mut self, top: &DynamicImage) -> Result<()> {
		self.ensure_same_size(top)?;
		overlay(self, top, 0, 0);
		Ok(())
	}

	#[allow(clippy::cast_possible_truncation)]
	fn overlay_additive(&mut self, top: &DynamicImage) -> Result<()> {
		self.ensure_same_size(top)?;

		// Helper: blend a single pixel given base (r,g,b,a) and top (r,g,b,a)
		fn blend(base_px: &[u8; 4], top_px: &[u8; 4]) -> [u8; 4] {
			let a_b = u16::from(base_px[3]);
			let a_t = u16::from(top_px[3]);
			let a_sum = a_b + a_t;
			if a_sum == 0 {
				return [0, 0, 0, 0];
			}

			// Snap near-opaque alpha to fully opaque to compensate for rounding
			let a_out = if a_sum >= 250 { 255 } else { a_sum };
			let a_b = a_out - a_t; // adjust base alpha to match snapped output
			[
				((u16::from(base_px[0]) * a_b + u16::from(top_px[0]) * a_t + a_out / 2) / a_out).min(255) as u8,
				((u16::from(base_px[1]) * a_b + u16::from(top_px[1]) * a_t + a_out / 2) / a_out).min(255) as u8,
				((u16::from(base_px[2]) * a_b + u16::from(top_px[2]) * a_t + a_out / 2) / a_out).min(255) as u8,
				a_out as u8,
			]
		}

		// RGB top is fully opaque and replaces base entirely
		if let DynamicImage::ImageRgb8(top_img) = top {
			*self = DynamicImage::ImageRgb8(top_img.clone());
			return Ok(());
		}

		let DynamicImage::ImageRgba8(top_img) = top else {
			bail!(
				"overlay_additive: unsupported top image type {:?}, expected RGB8 or RGBA8",
				top.color()
			);
		};

		match self {
			DynamicImage::ImageRgba8(base_img) => {
				for (base_px, top_px) in base_img.pixels_mut().zip(top_img.pixels()) {
					*base_px = image::Rgba(blend(&base_px.0, &top_px.0));
				}
			}
			DynamicImage::ImageRgb8(base_img) => {
				for (base_px, top_px) in base_img.pixels_mut().zip(top_img.pixels()) {
					let p = blend(&[base_px.0[0], base_px.0[1], base_px.0[2], 255], &top_px.0);
					*base_px = image::Rgb([p[0], p[1], p[2]]);
				}
			}
			_ => {
				bail!(
					"overlay_additive: unsupported base image type {:?}, expected RGB8 or RGBA8",
					self.color()
				);
			}
		}
		Ok(())
	}
}

/// Tests: alpha handling (drop/flatten/opaque), average color, scaling/cropping, overlays, and
/// color‑channel mutations using `rstest` parameterization where appropriate.
#[cfg(test)]
#[allow(clippy::cast_possible_truncation)]
mod tests {
	use super::*;
	use crate::traits::*;
	use image::ExtendedColorType as ECT;
	use image::{GenericImageView, Pixel, Rgba};
	use rstest::rstest;

	#[rstest]
	#[case::rgba(DynamicImage::new_test_rgba(), ECT::Rgb8, false)]
	#[case::la(DynamicImage::new_test_greya(), ECT::L8, false)]
	#[case::rgb(DynamicImage::new_test_rgb(), ECT::Rgb8, false)]
	#[case::grey(DynamicImage::new_test_grey(), ECT::L8, false)]
	fn to_no_alpha_drops_alpha_when_present(
		#[case] src: DynamicImage,
		#[case] expect_type: ECT,
		#[case] expect_has_alpha: bool,
	) {
		let out = src.to_no_alpha().unwrap();
		assert_eq!(out.extended_color_type(), expect_type);
		assert_eq!(out.has_alpha(), expect_has_alpha);
	}

	#[rstest]
	#[case::rgba(DynamicImage::new_test_rgba(), ECT::Rgb8)]
	#[case::la(DynamicImage::new_test_greya(), ECT::L8)]
	#[case::rgb(DynamicImage::new_test_rgb(), ECT::Rgb8)]
	#[case::grey(DynamicImage::new_test_grey(), ECT::L8)]
	fn into_no_alpha_variants(#[case] src: DynamicImage, #[case] expect_type: ECT) {
		let out = src.into_no_alpha().unwrap();
		assert_eq!(out.extended_color_type(), expect_type);
		assert!(!out.has_alpha());
	}

	#[test]
	fn average_color_on_solid_rgb_is_exact() {
		// Solid color should average to itself exactly (filtering can't change a constant)
		let img = DynamicImage::from_fn(11, 11, |x, y| {
			[100 - x as u8, 110 - y as u8, 120 + x as u8, 130 + y as u8]
		});
		assert_eq!(img.average_color(), [95, 105, 125, 135]);
	}

	#[rstest]
	#[case::grey(DynamicImage::new_test_grey(),&[128])]
	#[case::greya(DynamicImage::new_test_greya(),&[128,128])]
	#[case::rgb(DynamicImage::new_test_rgb(),&[128, 127, 128])]
	#[case::rgba(DynamicImage::new_test_rgba(),&[128, 127, 128, 127])]
	fn average_color_on_gradients_is_centerish(#[case] img: DynamicImage, #[case] expect: &[u8]) {
		assert_eq!(img.average_color(), expect);
	}

	#[rstest]
	#[case::rgba(DynamicImage::new_test_rgba(), Some((4usize, 3usize)))]
	#[case::la(DynamicImage::new_test_greya(), Some((2usize, 1usize)))]
	#[case::rgb(DynamicImage::new_test_rgb(), None)]
	#[case::luma(DynamicImage::new_test_grey(), None)]
	fn make_opaque_behaviour(
		#[case] mut img: DynamicImage,
		#[case] alpha_layout: Option<(usize, usize)>, // (stride, alpha_index)
	) {
		let before = img.as_bytes().to_vec();
		let has_alpha_before = img.has_alpha();

		img.make_opaque().unwrap();

		// Always opaque afterwards
		assert!(img.is_opaque());
		let after = img.as_bytes();

		if let Some((stride, aidx)) = alpha_layout {
			assert!(has_alpha_before, "expected an alpha channel");
			// Color bytes unchanged; alpha bytes set to 255
			for (i, (&a, &b)) in after.iter().zip(before.iter()).enumerate() {
				if i % stride == aidx {
					assert_eq!(a, 255, "alpha not set to 255 at byte index {i}");
				} else {
					assert_eq!(a, b, "color byte changed at index {i}");
				}
			}
			// Color type should remain the same (still has an alpha channel)
			assert!(img.has_alpha());
		} else {
			assert!(!has_alpha_before, "did not expect an alpha channel");
			// No-op for images without alpha: data unchanged
			assert_eq!(after, &before[..]);
			assert!(img.is_opaque());
		}
	}

	#[rstest]
	#[case::la(DynamicImage::new_test_greya(), ECT::La8, true, ECT::L8, false)]
	#[case::luma(DynamicImage::new_test_grey(), ECT::L8, false, ECT::L8, false)]
	#[case::rgb(DynamicImage::new_test_rgb(), ECT::Rgb8, false, ECT::Rgb8, false)]
	#[case::rgba(DynamicImage::new_test_rgba(), ECT::Rgba8, true, ECT::Rgb8, false)]
	fn into_no_alpha_if_opaque_behaviour(
		#[case] img: DynamicImage,
		#[case] expect_type_nonopaque: ECT,
		#[case] expect_has_alpha_nonopaque: bool,
		#[case] expect_type_opaque: ECT,
		#[case] expect_has_alpha_opaque: bool,
	) {
		// First: when image is not made opaque
		let out1 = img.clone().into_no_alpha_if_opaque().unwrap();
		assert_eq!(out1.extended_color_type(), expect_type_nonopaque);
		assert_eq!(out1.has_alpha(), expect_has_alpha_nonopaque);

		// Second: after forcing opacity (no-op for non-alpha images)
		let mut opaque_img = img.clone();
		opaque_img.make_opaque().unwrap();
		let out2 = opaque_img.into_no_alpha_if_opaque().unwrap();
		assert_eq!(out2.extended_color_type(), expect_type_opaque);
		assert_eq!(out2.has_alpha(), expect_has_alpha_opaque);
	}

	#[rstest]
	// No alpha: all bytes should become 0
	#[case::luma(DynamicImage::new_test_grey(), None)]
	#[case::rgb(DynamicImage::new_test_rgb(), None)]
	// With alpha: color bytes -> 0, alpha bytes unchanged
	#[case::luma_a(DynamicImage::new_test_greya(), Some((2usize, 1usize)))] // stride=2, alpha at index 1
	#[case::rgba(DynamicImage::new_test_rgba(), Some((4usize, 3usize)))] // stride=4, alpha at index 3
	fn map_color_values_applies_fn_to_all_color_channels(
		#[case] mut img: DynamicImage,
		#[case] alpha_layout: Option<(usize, usize)>, // (stride, alpha_index)
	) {
		let before = img.as_bytes().to_vec();
		img.map_color_values(|_| 0);
		let after = img.as_bytes();

		match alpha_layout {
			None => {
				// Luma8/Rgb8: everything zeroed
				assert!(after.iter().all(|&b| b == 0));
			}
			Some((stride, aidx)) => {
				// LumaA8/Rgba8: only alpha bytes preserved, colors zeroed
				for (i, (&a, &b)) in after.iter().zip(before.iter()).enumerate() {
					if i % stride == aidx {
						assert_eq!(a, b, "alpha channel changed at index {i}");
					} else {
						assert_eq!(a, 0, "color channel not zeroed at index {i}");
					}
				}
			}
		}
	}

	#[rstest]
	#[case::black(Rgba([0, 0, 0, 255]))]
	#[case::white(Rgba([255, 255, 255, 255]))]
	fn into_flattened_blends_with_background_when_alpha_present(#[case] bg: Rgba<u8>) {
		// Pattern: RGBA = [x, 255-x, y, 255-y]
		let rgba = DynamicImage::new_test_rgba();
		let flat = rgba.clone().into_flattened(bg.to_rgb()).unwrap();
		assert_eq!(flat.extended_color_type(), ECT::Rgb8);
		assert!(!flat.has_alpha());

		// Pixel at (10, 0): alpha = 255 -> unchanged
		let (x, y) = (10u32, 0u32);
		let p_src = rgba.get_pixel(x, y).0;
		let p_dst = flat.get_pixel(x, y).0;
		assert_eq!(&p_dst, &p_src);

		// Pixel at (20, 255): alpha = 0 -> becomes background color
		let (x, y) = (20u32, 255u32);
		let p_dst = flat.get_pixel(x, y).0;
		assert_eq!(p_dst, bg.0);
	}

	#[rstest]
	#[case::factor_1(1, (256, 256))]
	#[case::factor_2(2, (128, 128))]
	#[case::factor_4(4, (64, 64))]
	fn get_scaled_down_reduces_dimensions(#[case] factor: u32, #[case] expect_dims: (u32, u32)) {
		let img = DynamicImage::new_test_rgb();
		let out = img.clone().into_scaled_down(factor).unwrap();
		assert_eq!(out.dimensions(), expect_dims);
		let out2 = img.scaled_down(factor).unwrap();
		assert_eq!(out2.dimensions(), expect_dims);
	}

	#[test]
	fn get_extract_returns_requested_size() {
		let img = DynamicImage::new_test_rgb();
		// Crop a centered 128x128 region and request same-sized output
		let out = img.extract(64.0, 64.0, 128.0, 128.0, 128, 128).unwrap();
		assert_eq!(out.dimensions(), (128, 128));
		assert_eq!(out.extended_color_type(), ECT::Rgb8);
	}

	#[test]
	fn overlay_draws_top_over_bottom() {
		// Bottom: black RGB 16x16
		let mut bottom = DynamicImage::from_fn(16, 16, |_x, _y| [0, 0, 0]);
		// Top: solid red RGB 16x16
		let top = DynamicImage::from_fn(16, 16, |_x, _y| [255, 0, 0]);

		bottom.overlay(&top).unwrap();
		// A few sample pixels should now be red
		for &(x, y) in &[(0, 0), (8, 8), (15, 15)] {
			assert_eq!(bottom.get_pixel(x, y).0, [255, 0, 0, 255]);
		}
	}

	#[test]
	fn overlay_additive_non_overlapping_halves() {
		// Pixel A has alpha 128, pixel B has alpha 127 → together 255 (clamped)
		// color_A = 200, color_B = 100
		// color_out = (200*128 + 100*127 + 127) / 255 = (25600 + 12700 + 127) / 255 = 150
		let mut base = DynamicImage::from_raw(1, 1, vec![100u8, 100, 100, 127]).unwrap();
		let top = DynamicImage::from_raw(1, 1, vec![200u8, 200, 200, 128]).unwrap();

		base.overlay_additive(&top).unwrap();
		let px = base.get_pixel(0, 0).0;
		assert_eq!(px[3], 255); // alpha_out = min(255, 127 + 128) = 255
		// color_out = (100*127 + 200*128 + 127) / 255 = (12700 + 25600 + 127) / 255 = 150
		assert_eq!(px[0], 150);
		assert_eq!(px[1], 150);
		assert_eq!(px[2], 150);
	}

	#[test]
	fn overlay_additive_both_transparent() {
		// Both pixels fully transparent → result is transparent
		let mut base = DynamicImage::from_raw(1, 1, vec![100u8, 0, 0, 0]).unwrap();
		let top = DynamicImage::from_raw(1, 1, vec![200u8, 0, 0, 0]).unwrap();

		base.overlay_additive(&top).unwrap();
		let px = base.get_pixel(0, 0).0;
		// alpha_out = 0, colors should be unchanged (we skip when alpha_out == 0)
		assert_eq!(px[3], 0);
	}

	#[test]
	fn overlay_additive_partial_alpha() {
		// A: alpha=128 (0.502), B: alpha=64 (0.251) → alpha_out = 192 (0.753)
		// color_A = [255, 0, 0], color_B = [0, 0, 255]
		// r_out = (255*128 + 0*64 + 96) / 192 = (32640 + 96) / 192 = 170
		// b_out = (0*128 + 255*64 + 96) / 192 = (16320 + 96) / 192 = 85
		let mut base = DynamicImage::from_raw(1, 1, vec![0u8, 0, 255, 64]).unwrap();
		let top = DynamicImage::from_raw(1, 1, vec![255u8, 0, 0, 128]).unwrap();

		base.overlay_additive(&top).unwrap();
		let px = base.get_pixel(0, 0).0;
		assert_eq!(px[3], 192);
		assert_eq!(px[0], 170); // (255*128 + 0*64 + 96) / 192
		assert_eq!(px[1], 0);
		assert_eq!(px[2], 85); // (0*128 + 255*64 + 96) / 192
	}

	#[test]
	fn overlay_additive_alpha_clamps_at_255() {
		// A: alpha=200, B: alpha=200 → alpha_out = min(400, 255) = 255
		let mut base = DynamicImage::from_raw(1, 1, vec![100u8, 100, 100, 200]).unwrap();
		let top = DynamicImage::from_raw(1, 1, vec![100u8, 100, 100, 200]).unwrap();

		base.overlay_additive(&top).unwrap();
		let px = base.get_pixel(0, 0).0;
		assert_eq!(px[3], 255);
	}

	#[test]
	fn overlay_additive_rgb_copies_top() {
		let mut base = DynamicImage::from_fn(4, 4, |_x, _y| [0, 0, 0]);
		let top = DynamicImage::from_fn(4, 4, |_x, _y| [255, 128, 64]);

		base.overlay_additive(&top).unwrap();
		let px = base.get_pixel(0, 0).0;
		assert_eq!(px, [255, 128, 64, 255]);
	}

	#[test]
	fn overlay_additive_rgba_base_rgb_top() {
		// RGBA base with partial alpha, RGB top (fully opaque) → top dominates
		let mut base = DynamicImage::from_raw(1, 1, vec![0u8, 0, 255, 100]).unwrap();
		let top = DynamicImage::from_fn(1, 1, |_x, _y| [255, 0, 0]);

		base.overlay_additive(&top).unwrap();
		let px = base.get_pixel(0, 0).0;
		assert_eq!(px[3], 255); // 100 + 255 = 355 → clamped to 255
		// color_out = (0*100 + 255*255 + 127) / 255 ≈ 255
		assert_eq!(px[0], 255);
	}

	#[rstest]
	#[case::rgba_rgb(&[0, 0, 255, 100], &[255, 0, 0], &[255, 0, 0])]
	#[case::rgb_rgba(&[0, 0, 255], &[255, 0, 0, 100], &[100, 0, 155])]
	#[case::rgba_rgba(&[0, 0, 255, 100], &[255, 0, 0, 100], &[128, 0, 128, 200])]
	#[case::near_opaque_snaps_to_255(&[100, 100, 100, 125], &[100, 100, 100, 125], &[100, 100, 100, 255])]
	#[case::below_threshold_stays(&[100, 100, 100, 124], &[100, 100, 100, 125], &[100, 100, 100, 249])]
	fn overlay_additive(#[case] base_bytes: &[u8], #[case] top_bytes: &[u8], #[case] expect_color: &[u8]) {
		let mut base = DynamicImage::from_raw(1, 1, base_bytes.to_vec()).unwrap();
		let top = DynamicImage::from_raw(1, 1, top_bytes.to_vec()).unwrap();

		base.overlay_additive(&top).unwrap();
		let px = base.raw_pixel(0, 0);
		assert_eq!(px, expect_color);
	}

	#[test]
	fn overlay_additive_size_mismatch_errors() {
		let mut base = DynamicImage::from_raw(2, 2, vec![0u8; 16]).unwrap();
		let top = DynamicImage::from_raw(3, 3, vec![0u8; 36]).unwrap();
		assert!(base.overlay_additive(&top).is_err());
	}

	#[test]
	fn overlay_additive_unsupported_top_type_errors() {
		let mut base = DynamicImage::from_raw(2, 2, vec![0u8; 16]).unwrap(); // RGBA
		let top = DynamicImage::new_luma8(2, 2); // L8
		assert!(base.overlay_additive(&top).is_err());
	}

	#[test]
	fn overlay_additive_unsupported_base_type_errors() {
		let mut base = DynamicImage::new_luma8(2, 2); // L8
		let top = DynamicImage::from_raw(2, 2, vec![0u8; 16]).unwrap(); // RGBA
		assert!(base.overlay_additive(&top).is_err());
	}
}