From 5099477ca62fec1d7a994fb87567be0339a15187 Mon Sep 17 00:00:00 2001 From: Beinsezii Date: Fri, 28 Jun 2024 02:05:49 -0700 Subject: [PATCH] Round float before converting to u8 Else you get 0.999999 == 254 --- src/lib.rs | 2 +- src/tests.rs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 5988e13..3e0c93f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -903,7 +903,7 @@ pub fn srgb_to_irgb(pixel: [f32; N]) -> [u8; N] where Channels: ValidChannels, { - pixel.map(|c| ((c * 255.0).max(0.0).min(255.0) as u8)) + pixel.map(|c| ((c * 255.0).round().max(0.0).min(255.0) as u8)) } /// Create a hexadecimal string from integer RGB. diff --git a/src/tests.rs b/src/tests.rs index 58e1368..c8f7a0b 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -192,6 +192,11 @@ fn irgb_convert() { let mut srgba = irgb_to_srgb::(IRGBA); srgba.iter_mut().for_each(|c| *c = (*c * 100.0).round() / 100.0); assert_eq!([0.2, 0.35, 0.95, 0.35], srgba); + + // 254.4 / 255.0 ≈ 0.9970 // round up + // 254.6 / 255.0 ≈ 0.9984 // round down + let close_call = [0.9970, 0.9984, 0.999999]; + assert_eq!(srgb_to_irgb(close_call), [254, 255, 255]); } #[test]