From e6ee355f2e9ec5c295bf1694d490fdb6a61b987e Mon Sep 17 00:00:00 2001 From: Yusur Princeps Date: Thu, 18 Dec 2025 16:57:36 +0100 Subject: [PATCH] 0.12.0a3 add rgb <-> srgb --- CHANGELOG.md | 1 + src/suou/__init__.py | 2 +- src/suou/color.py | 36 ++++++++++++++++++++++++++++++++---- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21a7882..e28e673 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * All `AuthSrc()` derivatives, deprecated and never used, have been removed. * New module `mat` adds a shallow reimplementation of `Matrix()` in order to implement matrix multiplication * Removed obsolete `configparse` implementation that has been around since 0.3 and shelved since 0.4. +* `color`: added support for conversion from RGB to sRGB ## 0.11.2 diff --git a/src/suou/__init__.py b/src/suou/__init__.py index a0fbed1..06f5698 100644 --- a/src/suou/__init__.py +++ b/src/suou/__init__.py @@ -38,7 +38,7 @@ from .http import WantsContentType from .color import chalk, WebColor from .mat import Matrix -__version__ = "0.12.0a2" +__version__ = "0.12.0a3" __all__ = ( 'ConfigOptions', 'ConfigParserConfigSource', 'ConfigSource', 'ConfigValue', diff --git a/src/suou/color.py b/src/suou/color.py index 5a8b899..dfd2a6d 100644 --- a/src/suou/color.py +++ b/src/suou/color.py @@ -93,9 +93,9 @@ chalk = Chalk() ## Utilities for web colors -class WebColor(namedtuple('_WebColor', 'red green blue')): +class RGBColor(namedtuple('_WebColor', 'red green blue')): """ - Representation of a color in the TrueColor space (aka rgb). + Representation of a color in the RGB TrueColor space. Useful for theming. """ @@ -126,21 +126,49 @@ class WebColor(namedtuple('_WebColor', 'red green blue')): """ return self.darken(factor=factor) + self.lighten(factor=factor) - def blend_with(self, other: WebColor): + def blend_with(self, other: RGBColor): """ Mix two colors, returning the average. """ - return WebColor ( + return RGBColor ( (self.red + other.red) // 2, (self.green + other.green) // 2, (self.blue + other.blue) // 2 ) + def to_srgb(self): + """ + Convert to sRGB space. + + *New in 0.12.0* + """ + return SRGBColor(*( + (i / 12.92 if abs(c) <= 0.04045 else + (-1 if i < 0 else 1) * (((abs(c) + 0.55)) / 1.055) ** 2.4) for i in self + )) + __add__ = blend_with def __str__(self): return f"rgb({self.red}, {self.green}, {self.blue})" +WebColor = RGBColor + +## The following have been adapted from +## https://gist.github.com/dkaraush/65d19d61396f5f3cd8ba7d1b4b3c9432 + +class SRGBColor(namedtuple('_SRGBColor', 'red green blue')): + """ + Represent a color in the sRGB-Linear space. + + *New in 0.12.0* + """ + def to_rgb(self): + return RGBColor(*( + ((-1 if i < 0 else 1) * (1.055 * (abs(i) ** (1/2.4)) - 0.055) + if abs(i) > 0.0031308 else 12.92 * i) for i in self)) + + __all__ = ('chalk', 'WebColor')