Skip to content

add color type conversion #2444

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
add color type conversion
  • Loading branch information
Its-Just-Nans committed Mar 21, 2025
commit a620adb5d68cf7c1cc07149ae8ea5651b384687e
35 changes: 35 additions & 0 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,23 @@ impl ColorType {
let e: ExtendedColorType = self.into();
e.channel_count()
}

/// Returns the color type for a Pixel
pub fn from_type<P: Pixel, T>() -> Self {
match (P::CHANNEL_COUNT, size_of::<T>()) {
(1, 1) => ColorType::L8,
(1, 2) => ColorType::L16,
(2, 1) => ColorType::La8,
(2, 2) => ColorType::La16,
(3, 1) => ColorType::Rgb8,
(3, 2) => ColorType::Rgb16,
(3, 4) => ColorType::Rgb32F,
(4, 1) => ColorType::Rgba8,
(4, 2) => ColorType::Rgba16,
(4, 4) => ColorType::Rgba32F,
_ => panic!("Unsupported pixel type"),
}
}
}

/// An enumeration of color types encountered in image formats.
Expand Down Expand Up @@ -388,6 +405,12 @@ impl<T> Index<usize> for $ident<T> {
}
}

impl<T: $($bound+)*> From<$ident<T>> for ColorType {
fn from(_p: $ident<T>) -> Self {
ColorType::from_type::<$ident<T>, T>()
}
}

impl<T> IndexMut<usize> for $ident<T> {
#[inline(always)]
fn index_mut(&mut self, _index: usize) -> &mut T {
Expand Down Expand Up @@ -1044,4 +1067,16 @@ mod tests {
let Luma([luma]) = pixel.to_luma();
assert_eq!(luma, 13);
}

#[test]
fn test_color_type_from_color() {
use crate::color::ColorType;
use crate::color::Rgb;
let rgb: Rgb<u8> = Rgb([0, 0, 0]);
let color_type: ColorType = rgb.into();
assert_eq!(color_type, ColorType::Rgb8);
let rgb: Rgb<f32> = Rgb([0.0, 0.0, 0.0]);
let color_type: ColorType = rgb.into();
assert_eq!(color_type, ColorType::Rgb32F);
}
}