#rgba #bgra #pixel #color


struct RGB/RGBA/etc. for sharing pixels between crates + convenience methods for color manipulation. Allows no-copy high-level interoperability. Also adds common convenience methods and implements standard Rust traits to make RGB/RGBA pixels and slices first-class Rust objects.

10 releases

0.8.37 Oct 29, 2023
0.8.36 Feb 20, 2023
0.8.34 Sep 18, 2022
0.8.33 Jun 18, 2022
0.4.0 Jul 5, 2016

#21 in Images

Download history 193470/week @ 2023-11-03 208959/week @ 2023-11-10 140084/week @ 2023-11-17 137915/week @ 2023-11-24 129015/week @ 2023-12-01 177094/week @ 2023-12-08 182197/week @ 2023-12-15 91157/week @ 2023-12-22 143511/week @ 2023-12-29 190975/week @ 2024-01-05 168015/week @ 2024-01-12 151060/week @ 2024-01-19 136150/week @ 2024-01-26 144200/week @ 2024-02-02 160285/week @ 2024-02-09 118581/week @ 2024-02-16

586,242 downloads per month
Used in 906 crates (152 directly)

MIT license


struct RGB for Rust crate

Operating on pixels as weakly-typed vectors of u8 is error-prone and inconvenient. It's better to use vectors of pixel structs. However, Rust is so strongly typed that your RGB pixel struct is not compatible with my RGB pixel struct. So let's all use mine :P

xkcd standards


Add this to your Cargo.toml:

rgb = "0.8"


RGB and RGBA structs

The structs implement common Rust traits and a few convenience functions, e.g. map that repeats an operation on every subpixel:

use rgb::*; // Laziest way to use traits which add extra methods to the structs

let px = RGB {
let inverted = px.map(|ch| 255 - ch);

println!("{}", inverted); // Display: rgb(0,255,0)
assert_eq!(RGB8::new(0, 255, 0), inverted);

Byte slices to pixel slices

For interoperability with functions operating on generic arrays of bytes there are functions for safe casting to and from pixel slices.

let raw = vec![0u8; width*height*3];
let pixels: &[RGB8] = raw.as_rgb(); /// Safe casts without copying
let raw_again = pixels.as_bytes();

Note: if you get an error about "no method named as_bytes found", add use rgb::ComponentBytes. If you're using a custom component type (RGB<CustomType>), implement rgb::Pod (plain old data) and rgb::Zeroable trait for the component (these traits are from bytemuck crate).

About colorspaces

Correct color management is a complex problem, and this crate aims to be the lowest common denominator, so it's intentionally agnostic about it.

However, this library supports any subpixel type for RGB<T>, and RGBA<RGBType, AlphaType>, so you can use them with a newtype, e.g.:

struct LinearLight(u16);
type LinearRGB = RGB<LinearLight>;

BGRA, ARGB, Gray, etc.

There are other color types in rgb::alt::*. To enable ARGB and ABGR, use the "argb" feature:

rgb = { version = "0.8", features = ["argb"] }

There's also an optional serde feature that makes all types (de)serializable.