Skip to content

Commit

Permalink
Round float before converting to u8
Browse files Browse the repository at this point in the history
Else you get 0.999999 == 254
  • Loading branch information
Beinsezii committed Jun 28, 2024
1 parent f6adbe3 commit 5099477
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -903,7 +903,7 @@ pub fn srgb_to_irgb<const N: usize>(pixel: [f32; N]) -> [u8; N]
where
Channels<N>: 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.
Expand Down
5 changes: 5 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,11 @@ fn irgb_convert() {
let mut srgba = irgb_to_srgb::<f32, 4>(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]
Expand Down

0 comments on commit 5099477

Please sign in to comment.