#rgb #rgba #pixel #color #bgra

rgb

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.

37 releases

0.8.28 May 7, 2021
0.8.27 Mar 27, 2021
0.8.25 Aug 29, 2020
0.8.20 Jul 6, 2020
0.4.0 Jul 5, 2016

#5 in Images

Download history 22115/week @ 2021-07-04 20690/week @ 2021-07-11 20135/week @ 2021-07-18 30674/week @ 2021-07-25 19891/week @ 2021-08-01 32153/week @ 2021-08-08 28968/week @ 2021-08-15 44965/week @ 2021-08-22 37292/week @ 2021-08-29 31077/week @ 2021-09-05 31355/week @ 2021-09-12 26501/week @ 2021-09-19 22700/week @ 2021-09-26 48838/week @ 2021-10-03 29780/week @ 2021-10-10 43361/week @ 2021-10-17

56,305 downloads per month
Used in 264 crates (71 directly)

MIT license

69KB
1.5K SLoC

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

Installation

Add this to your Cargo.toml:

[dependencies]
rgb = "0.8"

Usage

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 {
    r:255_u8,
    g:0,
    b:255,
};
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.

Dependencies

~215KB