D
Documentation
v1.0.0
Usage Examples
This section provides practical examples of using Colorium in real-world scenarios.
Design System
Create a complete design system with colors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from colorium import Color, from_string, RED, BLUE, GREEN, YELLOW, WHITE, BLACK
class DesignSystem:
def __init__(self):
# Primary colors
self.primary = Color(66, 133, 244)
self.secondary = Color(234, 67, 53)
self.success = Color(52, 168, 83)
self.warning = Color(251, 188, 5)
self.error = Color(234, 67, 53)
# Neutrals
self.white = WHITE
self.black = BLACK
self.gray_100 = Color(245, 245, 245)
self.gray_200 = Color(200, 200, 200)
self.gray_300 = Color(150, 150, 150)
self.gray_400 = Color(100, 100, 100)
self.gray_500 = Color(50, 50, 50)
# Generate shades
self.primary_dark = self.primary.clone().darker(0.3)
self.primary_light = self.primary.clone().lighter(0.3)
self.primary_lightest = self.primary.clone().lighter(0.5)
def get_text_color(self, background):
"""Return appropriate text color for a given background"""
return BLACK if background.is_dark() else WHITE
def get_semantic_color(self, type):
"""Get color by semantic type"""
types = {
'primary': self.primary,
'success': self.success,
'warning': self.warning,
'error': self.error,
'info': Color(0, 150, 255)
}
return types.get(type, self.primary)
# Usage
design = DesignSystem()
print(f"Primary: {design.primary.to_hex_string()}")
print(f"Primary dark: {design.primary_dark.to_hex_string()}")
print(f"Primary light: {design.primary_light.to_hex_string()}")Data Visualization
Create color palettes for charts and graphs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from colorium import Color, from_hsl
def generate_palette(count, saturation=0.8, lightness=0.5):
"""Generate a set of distinct colors for visualization"""
palette = []
for i in range(count):
hue = (i / count) * 360
color = from_hsl(hue, saturation, lightness)
palette.append(color)
return palette
# Generate different palettes
sequential = generate_palette(5)
print("Sequential palette:")
for i, color in enumerate(sequential):
print(f" Color {i+1}: {color.to_hex_string()}")
# Diverging palette
def diverging_palette(count, center_color, min_color, max_color):
"""Create a diverging color palette"""
palette = []
half = count // 2
for i in range(count):
if i < half:
ratio = i / half
color = min_color.blend(center_color, ratio)
else:
ratio = (i - half) / (count - half)
color = center_color.blend(max_color, ratio)
palette.append(color)
return palette
# Example: Temperature palette (cold → neutral → hot)
cold = Color(0, 0, 255)
neutral = Color(128, 128, 128)
hot = Color(255, 0, 0)
temps = diverging_palette(7, neutral, cold, hot)
print("\nTemperature palette:")
for i, color in enumerate(temps):
print(f" Temp {i}: {color.to_hex_string()}")Image Processing
Basic color processing for images:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from colorium import Color, from_rgb
def average_color(pixels):
"""Calculate average color from a list of pixels"""
if not pixels:
return None
total_r = sum(p[0] for p in pixels)
total_g = sum(p[1] for p in pixels)
total_b = sum(p[2] for p in pixels)
n = len(pixels)
return from_rgb(total_r // n, total_g // n, total_b // n)
def dominant_color(pixels, threshold=30):
"""Find dominant color with tolerance"""
if not pixels:
return None
# Simple clustering by color proximity
clusters = []
for pixel in pixels:
color = from_rgb(pixel[0], pixel[1], pixel[2])
found = False
for cluster in clusters:
if color.delta_e(cluster['color'], "cie76") < threshold:
cluster['count'] += 1
found = True
break
if not found:
clusters.append({'color': color, 'count': 1})
# Find most common color
dominant = max(clusters, key=lambda x: x['count'])
return dominant['color']
# Example usage with sample pixels
sample_pixels = [
(255, 0, 0), (255, 50, 50), (255, 0, 0),
(0, 0, 255), (0, 50, 255), (0, 0, 255),
(255, 0, 0), (255, 0, 0)
]
avg = average_color(sample_pixels)
dom = dominant_color(sample_pixels)
print(f"Average color: {avg.to_hex_string() if avg else 'None'}")
print(f"Dominant color: {dom.to_hex_string() if dom else 'None'}")Theme Generation
Generate color themes and variants:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from colorium import Color, RED, BLUE, GREEN, from_hsl
def generate_theme(base_color):
"""Generate a complete theme from a base color"""
# Complementary
complementary = base_color.clone()
hsl = complementary.to_hsl()
complementary = from_hsl((hsl['h'] + 180) % 360, hsl['s'], hsl['l'])
# Analogous (3 colors on either side)
analogous = []
for i in [-30, 0, 30]:
color = from_hsl((hsl['h'] + i) % 360, hsl['s'], hsl['l'])
analogous.append(color)
# Triadic (3 colors 120° apart)
triadic = []
for i in [0, 120, 240]:
color = from_hsl((hsl['h'] + i) % 360, hsl['s'], hsl['l'])
triadic.append(color)
# Monochromatic (different lightness)
monochromatic = []
for i in [0.3, 0.5, 0.7, 0.9]:
color = from_hsl(hsl['h'], hsl['s'], i)
monochromatic.append(color)
return {
'base': base_color,
'complementary': complementary,
'analogous': analogous,
'triadic': triadic,
'monochromatic': monochromatic
}
# Generate theme from red
theme = generate_theme(RED)
print("Theme colors:")
print(f"Base: {theme['base'].to_hex_string()}")
print(f"Complementary: {theme['complementary'].to_hex_string()}")
print("Analogous:")
for color in theme['analogous']:
print(f" {color.to_hex_string()}")
print("Triadic:")
for color in theme['triadic']:
print(f" {color.to_hex_string()}")
print("Monochromatic:")
for color in theme['monochromatic']:
print(f" {color.to_hex_string()}")Color Accessibility
Check and ensure color accessibility:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from colorium import Color, from_string
class AccessibilityChecker:
def __init__(self):
self.WCAG_AA = 4.5
self.WCAG_AAA = 7.0
self.WCAG_AA_LARGE = 3.0
self.WCAG_AAA_LARGE = 4.5
def check_contrast(self, foreground, background, size='normal'):
"""Check contrast ratio between two colors"""
contrast = foreground.contrast_ratio(background)
if size == 'normal':
aa_pass = contrast >= self.WCAG_AA
aaa_pass = contrast >= self.WCAG_AAA
else:
aa_pass = contrast >= self.WCAG_AA_LARGE
aaa_pass = contrast >= self.WCAG_AAA_LARGE
return {
'ratio': contrast,
'aa_pass': aa_pass,
'aaa_pass': aaa_pass,
'level': 'AA' if aa_pass else 'Fail'
}
def suggest_text_color(self, background):
"""Suggest text color for a given background"""
white = Color(255, 255, 255)
black = Color(0, 0, 0)
white_contrast = background.contrast_ratio(white)
black_contrast = background.contrast_ratio(black)
return white if white_contrast > black_contrast else black
# Usage
checker = AccessibilityChecker()
# Check different combinations
backgrounds = [
Color(0, 0, 0), # Black
Color(255, 255, 255), # White
Color(66, 133, 244), # Blue
Color(234, 67, 53) # Red
]
for bg in backgrounds:
text = checker.suggest_text_color(bg)
result = checker.check_contrast(text, bg)
print(f"\nBackground: {bg.to_hex_string()}")
print(f"Suggested text: {text.to_hex_string()}")
print(f"Contrast ratio: {result['ratio']:.2f}:1")
print(f"WCAG AA: {'✓' if result['aa_pass'] else '✗'}")
print(f"WCAG AAA: {'✓' if result['aaa_pass'] else '✗'}")Brand Color Management
Work with brand colors and variations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from colorium import Color, from_string
class BrandColors:
def __init__(self, colors):
self.colors = {}
for name, color in colors.items():
if isinstance(color, str):
self.colors[name] = from_string(color)
else:
self.colors[name] = color
def get_color(self, name):
return self.colors.get(name)
def get_variant(self, name, variant):
color = self.colors.get(name)
if not color:
return None
variants = {
'light': lambda c: c.clone().lighter(0.3),
'dark': lambda c: c.clone().darker(0.3),
'darker': lambda c: c.clone().darker(0.5),
'lighter': lambda c: c.clone().lighter(0.5),
'desaturated': lambda c: c.clone().desaturate(0.3),
'saturated': lambda c: c.clone().saturate(0.3)
}
return variants.get(variant, lambda c: c)(color)
def to_dict(self):
return {name: color.to_hex_string() for name, color in self.colors.items()}
# Define brand colors
brand_colors = {
'primary': '#1A73E8',
'secondary': '#34A853',
'accent': '#EA4335',
'warning': '#FBBC04',
'background': '#FFFFFF',
'text': '#202124'
}
brand = BrandColors(brand_colors)
# Get color variants
print("Brand colors:")
for name, color in brand.colors.items():
print(f" {name}: {color.to_hex_string()}")
print("\nVariants:")
primary = brand.get_color('primary')
print(f"Primary original: {primary.to_hex_string()}")
print(f"Primary light: {brand.get_variant('primary', 'light').to_hex_string()}")
print(f"Primary dark: {brand.get_variant('primary', 'dark').to_hex_string()}")
print(f"Primary saturated: {brand.get_variant('primary', 'saturated').to_hex_string()}")Real-Time Color Processing
Process colors in real-time applications:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from colorium import Color, from_string
import time
class ColorProcessor:
def __init__(self):
self.history = []
def process(self, color, operation):
operations = {
'lighten': lambda c, a: c.clone().lighter(a),
'darken': lambda c, a: c.clone().darker(a),
'saturate': lambda c, a: c.clone().saturate(a),
'desaturate': lambda c, a: c.clone().desaturate(a),
'invert': lambda c, a: Color(255 - c.red, 255 - c.green, 255 - c.blue)
}
if operation not in operations:
raise ValueError(f"Unknown operation: {operation}")
if operation == 'invert':
result = operations[operation](color, None)
else:
result = operations[operation](color, 0.3)
self.history.append({
'original': color.to_hex_string(),
'operation': operation,
'result': result.to_hex_string(),
'timestamp': time.time()
})
return result
def undo(self):
if self.history:
return self.history.pop()
return None
def get_history(self):
return self.history
# Usage
processor = ColorProcessor()
color = Color(100, 150, 200)
print("Original color:", color.to_hex_string())
# Apply operations
processed = processor.process(color, 'lighten')
print("After lighten:", processed.to_hex_string())
processed = processor.process(processed, 'saturate')
print("After saturate:", processed.to_hex_string())
processed = processor.process(processed, 'invert')
print("After invert:", processed.to_hex_string())
# View history
print("\nProcessing history:")
for item in processor.get_history():
print(f" {item['operation']}: {item['original']} → {item['result']}")Gradient Generation
Create and interpolate gradients:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from colorium import Color, from_string
def create_gradient(start_color, end_color, steps=10):
"""Create a smooth gradient between two colors"""
gradient = []
for i in range(steps):
ratio = i / (steps - 1)
color = start_color.blend(end_color, ratio)
gradient.append(color)
return gradient
def multi_stop_gradient(colors, steps_per_segment=10):
"""Create a gradient with multiple color stops"""
if len(colors) < 2:
return colors
result = []
for i in range(len(colors) - 1):
segment = create_gradient(colors[i], colors[i+1], steps_per_segment)
if i > 0:
segment = segment[1:] # Avoid duplicate stops
result.extend(segment)
return result
# Create gradients
rainbow_colors = [
from_string("red"),
from_string("orange"),
from_string("yellow"),
from_string("green"),
from_string("blue"),
from_string("indigo"),
from_string("violet")
]
rainbow_gradient = multi_stop_gradient(rainbow_colors, 8)
print("Rainbow gradient:")
for i, color in enumerate(rainbow_gradient):
bar = "█" * 20
print(f"{i:2}: {color.to_hex_string()} {bar}")
# Simple two-color gradient
gradient = create_gradient(
from_string("red"),
from_string("blue"),
15
)
print("\nRed to Blue gradient:")
for color in gradient:
bar = "█" * 15
print(f"{color.to_hex_string()} {bar}")Previous: Quick Start Next: Core Concepts →
On this page
8 sections