Debian Codegraph @

README.md

raw symbols SCIP
1 # Palette
2
3 A color management and conversion library that focuses on maintaining correctness, flexibility and ease of use. It makes use of the type system to prevent mistakes, support a wide range of color spaces (including user defined variants) and offer different ways of integrating with other libraries.
4
5 [The announcement post for 0.7.6](https://ogeon.github.io/2024/04/28/palette-0.7.6.html).
6
7 ## Feature Summary
8
9 * Type system representations of color spaces, including RGB, HSL, HSV, HWB, L\*a\*b\*, L\*C\*h°, XYZ and xyY.
10 * Copy free conversion to and from color buffers allows simple integration with other crates and systems.
11 * Color operations implemented as traits, such as arithmetic, lighten/darken, hue shifting, mixing/interpolating, and SVG blend functions.
12 * Color spaces can be customized, using type parameters, to support different levels of precision, linearity, white points, RGB standards, etc.
13 * Supports `#[no_std]`.
14 * Optional `serde`, `rand`, and `bytemuck` integration.
15
16 ## Minimum Supported Rust Version (MSRV)
17
18 This version of Palette has been automatically tested with Rust version `1.60.0` and the `stable`, `beta`, and `nightly` channels. Future versions of the library may advance the minimum supported version to make use of new language features, but this will normally be considered a breaking change. Exceptions may be made for security patches, dependencies advancing their MSRV in minor or patch releases, and similar changes.
19
20 ## Getting Started
21
22 Add the following lines to your `Cargo.toml` file:
23
24 ```toml
25 [dependencies]
26 palette = "0.7.6"
27 ```
28
29 or these lines if you want to opt out of `std`:
30
31 ```toml
32 [dependencies.palette]
33 version = "0.7.6"
34 default-features = false
35 features = ["libm"] # Uses libm instead of std for floating point math
36 ```
37
38 ### Cargo Features
39
40 These features are enabled by default:
41
42 * `"named"` - Enables color constants, located in the `named` module.
43 * `"named_from_str"` - Enables `named::from_str`, which maps name strings to colors.
44 * `"std"` - Enables use of the standard library. Also enables `"alloc"`.
45 * `"alloc"` - Enables implementations for allocating types, such as `Vec` or `Box`.
46 * `"approx"` - Enables approximate comparison using [`approx`].
47
48 These features are disabled by default:
49
50 * `"serializing"` - Enables color serializing and deserializing using [`serde`].
51 * `"random"` - Enables generating random colors using [`rand`].
52 * `"libm"` - Uses the [`libm`] floating point math library (for when the `std` feature is disabled).
53 * `"bytemuck"` - Enables casting between plain data types using [`bytemuck`].
54 * `"wide"` - Enables support for using SIMD types from [`wide`].
55 * `"find-crate"` - Enables derives to find the `palette` crate when it's renamed in `Cargo.toml`.
56
57 ### Using palette in an embedded environment
58
59 Palette supports `#![no_std]` environments by disabling the `"std"` feature. It uses [`libm`], via the `"libm"` feature, to provide the floating-point operations that are typically in `std`, and the `"alloc"` feature to provide features that use allocating types. However, serializing with `serde` is not available without the standard library.
60
61 ## Examples
62
63 These are examples of some of the features listed in the feature summary.
64
65 ### Converting
66
67 It's possible to convert from one color space to another with the `FromColor` and `IntoColor` traits. They are similar to `From` and `Into`, but tailored for colors:
68
69 ```rust
70 use palette::{FromColor, Hsl, IntoColor, Lch, Srgb};
71
72 let my_rgb = Srgb::new(0.8, 0.3, 0.3);
73
74 let mut my_lch = Lch::from_color(my_rgb);
75 my_lch.hue += 180.0;
76
77 let mut my_hsl: Hsl = my_lch.into_color();
78 my_hsl.lightness *= 0.6;
79
80 let my_new_rgb = Srgb::from_color(my_hsl);
81 ```
82
83 This image shows the starting color and the results of the two changes:
84
85 ![The result of each step in the "converting" example.](https://raw.githubusercontent.com/Ogeon/palette/05e60121f3ab39aba972c477f258c70d0495551d/gfx/readme_converting.png)
86
87 Most of the common color spaces are already implemented in Palette, but some situations may require something more customized. The conversion traits make it possible to integrate custom color types into the system. For example, this can be used for adding new color spaces or making a simpler user-facing API.
88
89 A longer and more advanced example that shows how to implement the conversion traits for a custom color type can be found further down.
90
91 ### Pixels And Buffers
92
93 When working with image or pixel buffers, or any color type that can be converted to a slice of components (ex. `&[u8]`), the `cast` module provides traits and functions for turning them into slices of Palette colors without cloning the whole buffer:
94
95 ```rust
96 use palette::{cast::ComponentsAsMut, Srgb};
97
98 // The input to this function could be data from an image file or
99 // maybe a texture in a game.
100 fn swap_red_and_blue(my_rgb_image: &mut [u8]) {
101 // Convert `my_rgb_image` into `&mut [Srgb<u8>]` without copying.
102 let my_rgb_image: &mut [Srgb<u8>] = my_rgb_image.components_as_mut();
103
104 for color in my_rgb_image {
105 std::mem::swap(&mut color.red, &mut color.blue);
106 }
107 }
108 ```
109
110 | Before | After |
111 |--------|-------|
112 | ![The fruit image before swapping the red and blue color channels.](https://raw.githubusercontent.com/Ogeon/palette/05e60121f3ab39aba972c477f258c70d0495551d/example-data/input/fruits-128.png) | ![The fruit image with the red and blue color channels swapped.](https://raw.githubusercontent.com/Ogeon/palette/05e60121f3ab39aba972c477f258c70d0495551d/gfx/readme_pixels_and_buffers.png) |
113
114 It's also possible to create a single color from a slice or array. Let's say we are using something that implements `AsMut<[u8; 3]>`:
115
116 ```rust
117 use palette::Srgb;
118
119 fn swap_red_and_blue(mut my_rgb: impl AsMut<[u8; 3]>) {
120 let my_rgb: &mut Srgb<u8> = my_rgb.as_mut().into();
121
122 std::mem::swap(&mut my_rgb.red, &mut my_rgb.blue);
123 }
124 ```
125
126 This makes it possible to use Palette with any other crate that can convert their color types to slices and arrays, with minimal glue code and little to no overhead. It's also possible to go the opposite direction and convert Palette types to slices and arrays.
127
128 ### Color Operations
129
130 Palette comes with a number of color operations built in, such as saturate/desaturate, hue shift, etc., in the form of operator traits. That means it's possible to write generic functions that perform these operation on any color space that supports them. The output will vary depending on the color space's characteristics.
131
132 ```rust
133 use palette::{Hsl, Hsv, Lighten, Mix, ShiftHue};
134
135 fn transform_color<C>(color: C, amount: f32) -> C
136 where
137 C: ShiftHue<Scalar = f32> + Lighten<Scalar = f32> + Mix<Scalar = f32> + Copy,
138 {
139 let new_color = color.shift_hue(170.0).lighten(1.0);
140
141 // Interpolate between the old and new color.
142 color.mix(new_color, amount)
143 }
144
145 let new_hsl = transform_color(Hsl::new_srgb(0.00, 0.70, 0.20), 0.8);
146 let new_hsv = transform_color(Hsv::new_srgb(0.00, 0.82, 0.34), 0.8);
147 ```
148
149 This image shows the transition from the color to `new_color` in HSL and HSV:
150
151 ![Gradients showing the transition from the starting color to the modified color in HSL and HSV.](https://raw.githubusercontent.com/Ogeon/palette/05e60121f3ab39aba972c477f258c70d0495551d/gfx/readme_color_operations_1.png)
152
153 In addition to the operator traits, the SVG blend and composition functions have also been implemented.
154
155 ```rust
156 use palette::{
157 blend::Compose,
158 cast::{ComponentsAs, ComponentsAsMut},
159 Srgb, WithAlpha,
160 };
161
162 // The input to this function could be data from image files.
163 fn alpha_blend_images(image1: &mut [u8], image2: &[u8]) {
164 // Convert the images into `&mut [Srgb<u8>]` and `&[Srgb<u8>]` without copying.
165 let image1: &mut [Srgb<u8>] = image1.components_as_mut();
166 let image2: &[Srgb<u8>] = image2.components_as();
167
168 for (color1, color2) in image1.iter_mut().zip(image2) {
169 // Convert the colors to linear floating point format and give them transparency values.
170 let color1_alpha = color1.into_linear().opaque();
171 let color2_alpha = color2.into_linear().with_alpha(0.5);
172
173 // Alpha blend `color2_alpha` over `color1_alpha`.
174 let blended = color2_alpha.over(color1_alpha);
175
176 // Convert the color part back to `Srgb<u8>` and overwrite the value in image1.
177 *color1 = blended.color.into_encoding();
178 }
179 }
180 ```
181
182 | Image 1 | Image 2 | Result |
183 |---------|---------|--------|
184 | ![A photo of various fruit.](https://raw.githubusercontent.com/Ogeon/palette/05e60121f3ab39aba972c477f258c70d0495551d/example-data/input/fruits-128.png) | ![A photo of kitten in a strawhat.](https://raw.githubusercontent.com/Ogeon/palette/05e60121f3ab39aba972c477f258c70d0495551d/example-data/input/cat-128.png) |![Image 2 blended over Image 1 with 50% transparency.](https://raw.githubusercontent.com/Ogeon/palette/05e60121f3ab39aba972c477f258c70d0495551d/gfx/readme_color_operations_2.png)
185
186 There's also the option to explicitly convert to and from premultiplied alpha, to avoid converting back and forth more than necessary, using the `PreAlpha` type.
187
188 ### Gradients
189
190 Most color types are directly compatible with gradient and interpolation crates, such as [`enterpolation`]:
191
192 ```rust
193 use enterpolation::{linear::ConstEquidistantLinear, Curve};
194 use palette::LinSrgb;
195
196 let gradient = ConstEquidistantLinear::<f32, _, 3>::equidistant_unchecked([
197 LinSrgb::new(0.00, 0.05, 0.20),
198 LinSrgb::new(0.70, 0.10, 0.20),
199 LinSrgb::new(0.95, 0.90, 0.30),
200 ]);
201
202 let taken_colors: Vec<_> = gradient.take(10).collect();
203 ```
204
205 Here's the gradient as both its continuous form and as the 10 colors from `.take(10)`:
206
207 ![An illustration of the gradient with the continuous form above a row of discrete color swatches.](https://raw.githubusercontent.com/Ogeon/palette/05e60121f3ab39aba972c477f258c70d0495551d/gfx/readme_gradients_1.png)
208
209 ### Customizing Color Spaces
210
211 The built-in color spaces have been made customizable to account for as much variation as possible. The more common variants have been exposed as type aliases (like `Srgb`, `Srgba` and `LinSrgb` from above), but it's entirely possible to make custom compositions, including with entirely new parameters. For example, making up your own RGB standard:
212
213 ```rust
214 use palette::{
215 encoding,
216 white_point,
217 rgb::Rgb,
218 chromatic_adaptation::AdaptFrom,
219 Srgb
220 };
221
222 // RgbStandard and RgbSpace are implemented for 2 and 3 element tuples,
223 // allowing mixing and matching of existing types. In this case we are
224 // combining sRGB primaries, the CIE equal energy white point and the
225 // sRGB transfer function (a.k.a. encoding or gamma).
226 type EqualEnergyStandard = (encoding::Srgb, white_point::E, encoding::Srgb);
227 type EqualEnergySrgb<T> = Rgb<EqualEnergyStandard, T>;
228
229 let ee_rgb = EqualEnergySrgb::new(1.0, 0.5, 0.3);
230
231 // We need to use chromatic adaptation when going between white points.
232 let srgb = Srgb::adapt_from(ee_rgb);
233 ```
234
235 It's also possible to implement the traits for a custom type, for when the built-in options are not enough.
236
237 ### Converting Custom Color Types
238
239 The following example shows how it's possible for Palette users to convert from and into a custom made `Color` type. It's not exactly a one-liner, but it can still save a lot of repetitive manual work.
240
241 ```rust
242 use palette::{
243 convert::FromColorUnclamped,
244 encoding,
245 rgb::Rgb,
246 IntoColor, WithAlpha, Clamp, Srgb, Lcha
247 };
248
249 // This implements conversion to and from all Palette colors.
250 #[derive(FromColorUnclamped, WithAlpha)]
251 // We have to tell Palette that we will take care of converting to/from sRGB.
252 #[palette(skip_derives(Rgb), rgb_standard = "encoding::Srgb")]
253 struct Color {
254 r: f32,
255 g: f32,
256 b: f32,
257 // Let Palette know this is our alpha channel.
258 #[palette(alpha)]
259 a: f32,
260 }
261
262 // There's no blanket implementation for Self -> Self, unlike the From trait.
263 // This is to better allow cases like Self<A> -> Self<B>.
264 impl FromColorUnclamped<Color> for Color {
265 fn from_color_unclamped(color: Color) -> Color {
266 color
267 }
268 }
269
270 // Convert from any kind of f32 sRGB.
271 impl<S> FromColorUnclamped<Rgb<S, f32>> for Color
272 where
273 Srgb: FromColorUnclamped<Rgb<S, f32>>,
274 {
275 fn from_color_unclamped(color: Rgb<S, f32>) -> Color {
276 let srgb = Srgb::from_color_unclamped(color);
277 Color { r: srgb.red, g: srgb.green, b: srgb.blue, a: 1.0 }
278 }
279 }
280
281 // Convert into any kind of f32 sRGB.
282 impl<S> FromColorUnclamped<Color> for Rgb<S, f32>
283 where
284 Rgb<S, f32>: FromColorUnclamped<Srgb>,
285 {
286 fn from_color_unclamped(color: Color) -> Self {
287 let srgb = Srgb::new(color.r, color.g, color.b);
288 Self::from_color_unclamped(srgb)
289 }
290 }
291
292 // Add the required clamping.
293 impl Clamp for Color {
294 fn clamp(self) -> Self {
295 Color {
296 r: self.r.min(1.0).max(0.0),
297 g: self.g.min(1.0).max(0.0),
298 b: self.b.min(1.0).max(0.0),
299 a: self.a.min(1.0).max(0.0),
300 }
301 }
302 }
303
304
305 // This function uses only our `Color`, but Palette users can convert to it.
306 fn do_something(color: Color) {
307 // ...
308 }
309
310 do_something(Color { r: 1.0, g: 0.0, b: 1.0, a: 0.5 });
311 do_something(Lcha::new(60.0, 116.0, 328.0, 0.5).into_color());
312
313
314 // This function has the conversion built in and takes any compatible
315 // color type as input.
316 fn generic_do_something(color: impl IntoColor<Color>) {
317 let color = color.into_color();
318 // ...
319 }
320
321 generic_do_something(Color { r: 1.0, g: 0.0, b: 1.0, a: 0.5 });
322 generic_do_something(Lcha::new(60.0, 116.0, 328.0, 0.5));
323 ```
324
325 ## License
326
327 Licensed under either of
328
329 * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
330 * MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
331
332 at your option.
333
334 [`serde`]: https://crates.io/crates/serde
335 [`rand`]: https://crates.io/crates/rand
336 [`libm`]: https://crates.io/crates/libm
337 [`bytemuck`]: https://crates.io/crates/bytemuck
338 [`wide`]: https://crates.io/crates/wide
339 [`approx`]: https://crates.io/crates/approx
340 [`enterpolation`]: https://crates.io/crates/enterpolation