From 38456b67a943f39dfad7ab35589afe7a86ea4643 Mon Sep 17 00:00:00 2001 From: "A. Molzer" <5550310+197g@users.noreply.github.com> Date: Thu, 4 Sep 2025 17:38:22 +0200 Subject: [PATCH] Add utility from_raw_bgr{,a} for ImageBuffer It is one of the most common channel orders other than Rgb and the construction involves nothing complicated, just swapping the channels around. We don't support that layout during computation, where it would complicate significant parts of `Pixel`, but as a helper for transferring a buffer we can easily have both on the `Rgb{,A}` typed containers. --- src/images/buffer.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/images/buffer.rs b/src/images/buffer.rs index 6227a0ef25..59a93bdaf2 100644 --- a/src/images/buffer.rs +++ b/src/images/buffer.rs @@ -1406,6 +1406,60 @@ impl ImageBuffer> { } } +impl ImageBuffer, Container> +where + S: crate::Primitive + crate::traits::Enlargeable, + Rgb: Pixel, + Container: DerefMut as Pixel>::Subpixel]>, +{ + /// Construct an image by swapping `Bgr` channels into an `Rgb` order. + pub fn from_raw_bgr(width: u32, height: u32, container: Container) -> Option { + let mut img = Self::from_raw(width, height, container)?; + + for pix in img.pixels_mut() { + pix.0.reverse(); + } + + Some(img) + } + + /// Return the underlying raw buffer after converting it into `Bgr` channel order. + pub fn into_raw_bgr(mut self) -> Container { + for pix in self.pixels_mut() { + pix.0.reverse(); + } + + self.into_raw() + } +} + +impl ImageBuffer, Container> +where + S: crate::Primitive + crate::traits::Enlargeable, + Rgb: Pixel, + Container: DerefMut as Pixel>::Subpixel]>, +{ + /// Construct an image by swapping `BgrA` channels into an `RgbA` order. + pub fn from_raw_bgra(width: u32, height: u32, container: Container) -> Option { + let mut img = Self::from_raw(width, height, container)?; + + for pix in img.pixels_mut() { + pix.0[..3].reverse(); + } + + Some(img) + } + + /// Return the underlying raw buffer after converting it into `BgrA` channel order. + pub fn into_raw_bgra(mut self) -> Container { + for pix in self.pixels_mut() { + pix.0[..3].reverse(); + } + + self.into_raw() + } +} + /// Provides color conversions for whole image buffers. pub trait ConvertBuffer { /// Converts `self` to a buffer of type T