Debian Codegraph @

README

raw
1 NAME
2 Graphics::Toolkit::Color - calculate color (sets), IO many spaces and
3 formats
4
5 SYNOPSIS
6 use Graphics::Toolkit::Color qw/color/;
7
8 my $red = Graphics::Toolkit::Color->new('red'); # create color object
9 say $red->add_value( 'blue' => 255 )->name; # red + blue = 'magenta'
10 my @blue = color( 0, 0, 255)->values('HSL'); # 240, 100, 50 = blue
11 $red->mix( to => [HSL => 0,0,80], amount => 10); # mix red with a little grey
12 $red->gradient( to => '#0000FF', steps => 10); # 10 colors from red to blue
13 my @base_triadic = $red->complement( 3 ); # get fitting red green and blue
14 my @reds = $red->cluster( radius => 4, distance => 1 );
15
16 DEPRECATION WARNING
17 Methods of the old API ( *string*, *rgb*, *red*, *green*, *blue*,
18 *rgb_hex*, *rgb_hash*, *hsl*, *hue*, *saturation*, *lightness*,
19 *hsl_hash*, *add*, *set*, *blend*, *blend_with*, *gradient_to*,
20 *rgb_gradient_to*, *hsl_gradient_to*, *complementary*) will be removed
21 with release of version 2.0.
22
23 DESCRIPTION
24 Graphics::Toolkit::Color, for short GTC, is the top level API of this
25 release and the only package a regular user should be concerned with.
26 Its main purpose is the creation of related colors or sets of them, such
27 as gradients, complements and others. But you can use it also to convert
28 and/or reformat color definitions.
29
30 GTC are read only, one color representing objects with no additional
31 dependencies. Create them in many different ways (see "CONSTRUCTOR").
32 Access its values via methods from section "GETTER". Measure differences
33 with the "distance" method. "SINGLE-COLOR" methods create one new object
34 that is related to the current one and "COLOR-SETS" methods will create
35 a group of colors, that are not only related to the current color but
36 also have relations between each other. Error messages will appear as
37 return values instead of the expected result.
38
39 While this module can understand and output color values to many color
40 spaces, RGB is the (internal) primal one, because GTC is about colors
41 that can be shown on the screen, and these are usually encoded in *RGB*.
42 Humans access colors on hardware level (eye) in *RGB*, on cognition
43 level in *HSL* (brain) and on cultural level (language) with names.
44 Having easy access to all of those plus some color math and many formats
45 should enable you to get the color palette you desire quickly.
46
47 CONSTRUCTOR
48 There are many options to create a color object. In short you can either
49 use the name of a constant (see "name") or provide values, which are
50 coordinates in one of several color spaces. The latter are also
51 understood in many formats. From now on any input that the constructor
52 method "new" accepts, is called a color definition.
53
54 new({ r => $r, g => $g, b => $b })
55 Most clear, flexible and longest input format: a hash with long or short
56 axis names as keys with fitting values. This can be "red", "green" and
57 "blue" or "r", "g" and "b" or names from any other color space. Upper or
58 lower case doesn't matter.
59
60 my $red = Graphics::Toolkit::Color->new( r => 255, g => 0, b => 0 );
61 my $red = Graphics::Toolkit::Color->new({r => 255, g => 0, b => 0}); # works too
62 ... ->new( Red => 255, Green => 0, Blue => 0); # also fine
63 ... ->new( Hue => 0, Saturation => 100, Lightness => 50 ); # same color
64 ... ->new( Hue => 0, whiteness => 0, blackness => 0 ); # still the same
65
66 new( [$r, $g, $b] )
67 takes a triplet of integer *RGB* values (red, green and blue : 0 ..
68 255). They can, but don't have to be put into an ARRAY reference (square
69 brackets). If you want to define a color by values from another color
70 space, you have to prepend the values with the name of a supported color
71 space. Out of range values will be corrected (clamped).
72
73 my $red = Graphics::Toolkit::Color->new( 255, 0, 0 );
74 my $red = Graphics::Toolkit::Color->new( [255, 0, 0]); # does the same
75 my $red = Graphics::Toolkit::Color->new( 'RGB', 255, 0, 0 ); # named ARRAY syntax
76 my $red = Graphics::Toolkit::Color->new( RGB => 255, 0, 0 ); # with fat comma
77 my $red = Graphics::Toolkit::Color->new([ RGB => 255, 0, 0]); # and brackets
78 my $red = Graphics::Toolkit::Color->new( RGB =>[255, 0, 0]); # separate name and values
79 my $red = Graphics::Toolkit::Color->new( YUV =>.299,-0.168736, .5); # same color in YUV
80
81 new('rgb($r,$g,$b)')
82 String format that is supported by CSS (*css_string* format): it starts
83 with the case insensitive color space name (lower case is default),
84 followed by the (optionally with) comma separated values in round
85 braces. The value suffixes that are defined by the color space (*'%'* in
86 case of *HSV*) are optional.
87
88 my $red = Graphics::Toolkit::Color->new( 'rgb(255 0 0)' );
89 my $blue = Graphics::Toolkit::Color->new( 'hsv(240, 100%, 100%)' );
90
91 new('rgb: $r, $g, $b')
92 String format *named_string* (good for serialisation) that maximizes
93 readability.
94
95 my $red = Graphics::Toolkit::Color->new( 'rgb: 255, 0, 0' );
96 my $blue = Graphics::Toolkit::Color->new( 'HSV: 240, 100, 100' );
97
98 new('#rgb')
99 Color definitions in hexadecimal format as widely used in the web, are
100 also acceptable (*RGB* only).
101
102 my $color = Graphics::Toolkit::Color->new('#FF0000');
103 my $color = Graphics::Toolkit::Color->new('#f00'); # short works too
104
105 new('name')
106 Get a color object by providing a name from the X11, HTML (CSS) or SVG
107 scheme or a Pantone report. UPPER or CamelCase will be normalized to
108 lower case and inserted underscore letters ('_') will be ignored as perl
109 does in numbers (1_000 == 1000). All available names are listed here .
110
111 my $color = Graphics::Toolkit::Color->new('Emerald');
112 my @names = Graphics::Toolkit::Color::Name::all(); # select from these
113
114 new('scheme:color')
115 Get a color by name from a specific scheme or standard as provided by an
116 external module Graphics::ColorNames::* , which has to be installed
117 separately or with Bundle::Graphics::ColorNames. See all scheme names
118 here . The color name will be normalized as above.
119
120 my $color = Graphics::Toolkit::Color->new('SVG:green');
121 my @schemes = Graphics::ColorNames::all_schemes(); # look up the installed
122
123 color
124 If writing
125
126 Graphics::Toolkit::Color->new( ...);
127
128 is too much typing work for you or takes up to much space in the code
129 file, import the subroutine "color", which accepts all the same
130 arguments as "new".
131
132 use Graphics::Toolkit::Color qw/color/;
133 my $green = color('green');
134 my $darkblue = color([20, 20, 250]);
135
136 GETTER
137 giving access to different parts of the objects data.
138
139 values
140 Returns the numeric values of the color, held by the object. The method
141 accepts five optional, named arguments: "in" (color space), "as"
142 (format), "range", "precision" and "suffix". In most cases, only the
143 first one is needed.
144
145 When given no arguments, the method returns a list with the integer
146 values: "red", "green" and "blue" in 0 .. 255 range, since *RGB* is the
147 default color space of this module.
148
149 If one positional argument is provided, the values get converted into
150 the color space of the given name. The same is done when using the named
151 argument "in" (full explanation behind the link). The named argument
152 "range" is also explained in its own section. Please note you have to
153 use the "range" argument only, if you like to deviate from the value
154 ranges defined by the chosen color space.
155
156 The maybe most characteristic argument for this method is "as", which
157 enables all the same formats the constructor method "new" accepts. *GTC*
158 is built with the design principle of total serialisation. This means:
159 every contructor input format can be reproduced by a getter method and
160 vice versa. These formats are: "list" (default), "named_array", "hash",
161 "char_hash", "named_string", "css_string", "array" (RGB only) and
162 "hex_string" (RGB only). The remaining two. "name" and "full:name" are
163 produce by the method "name". Format names are case insensitive. For
164 more explanations, please see: formats section in GTC::Space::Hub.
165
166 "precision" is more exotic argument, but sometimes you need to escape
167 the numeric precision, set by a color spaces definition. For instance
168 "LAB" values will have maximally three decimals, no matter how precise
169 the input was. In case you prefer 4 decimals, just use "precision => 4".
170 A zero means no decimals and -1 stands for maximal precision - which can
171 spit out more decimals than you prefer. Different precisions per axis
172 are possible via an ARRAY ref: "precision => [1,2,3]".
173
174 In same way you can atach a little strings per value by ussing the
175 "suffix" argument. Normally these are percentage signs but in some
176 spaces, where they appear by default you can surpress them by adding
177 "suffix => ''"
178
179 $blue->values(); # 0, 0, 255
180 $blue->values( in => 'RGB', as => 'list'); # 0, 0, 255 # explicit arguments
181 $blue->values( as => 'array'); # [0, 0, 255] - RGB only
182 $blue->values( in => 'RGB', as => 'named_array'); # ['RGB', 0, 0, 255]
183 $blue->values( in => 'RGB', as => 'hash'); # { red => 0, green => 0, blue => 255}
184 $blue->values( in => 'RGB', as => 'char_hash'); # { r => 0, g => 0, b => 255}
185 $blue->values( in => 'RGB', as => 'named_string'); # 'rgb: 0, 0, 255'
186 $blue->values( in => 'RGB', as => 'css_string'); # 'rgb( 0, 0, 255)'
187 $blue->values( as => 'hex_string'); # '#0000ff' - RGB only
188 $blue->values( range => 2**16 ); # 0, 0, 65536
189 $blue->values('HSL'); # 240, 100, 50
190 $blue->values( in => 'HSL',suffix => ['', '%','%']);# 240, '100%', '50%'
191 $blue->values( in => 'HSB', as => 'hash')->{'hue'};# 240
192 ($blue->values( 'HSB'))[0]; # 240
193 $blue->values( in => 'XYZ', range => 1, precision => 2);# normalized, 2 decimals max.
194
195 name
196 Returns the normalized name string (lower case, without *'_'*) that
197 represents the *RGB* values of this color in the default color scheme,
198 which is *X11* + *HTML* (*SVG*) + *Pantone report* (see all names).
199 These are the same which can be used with "new('name')".
200
201 Alternatively you may provide named arguments or one positional
202 argument, which is the same as the named argument "from". That required
203 a name of a color schemes, as listed here. You also can submit a list
204 thereof inside a ARRRAY ref which also dictates the order of resulting
205 color names. Please note that all color schemes, except the default one,
206 depend on external modules, which have to be installed separately or via
207 Bundle::Graphics::ColorNames. If you try to use a scheme from a not
208 installed module your will get an error message instead of a color name.
209 You can also create your custom color naming scheme via
210 Graphics::Toolkit::Color::Name::Scheme.
211
212 The second named argument is "all", which needs to be a perly boolean.
213 It defaults to false. But if set to 1, you will get a list of all names
214 that are associated with the current values. There will be no
215 duplicates, when several schemes are searched.
216
217 A third named argument is "full" - also needing a perly boolean that
218 defaults to false. When set "true" (1), the schema name becomes part of
219 the returned color name as in 'SVG:red'. These full names are also
220 accepted by the constructor.
221
222 The fourth named argument is "distance", which means the same thing as
223 in "distance" and it defaults to zero. It is most useful in combinataion
224 with "all" to get all color names that are within a certain distance.
225
226 $blue->name(); # 'blue'
227 $blue->name('SVG'); # 'blue'
228 $blue->name( from => [qw/CSS X/], all => 1); # 'blue', 'blue1'
229 $blue->name( from => 'CSS', full => 1); # 'CSS:blue'
230 $blue->name( distance => 3, all => 1) ; # all names within the distance
231
232 closest_name
233 Returns in scalar context a color name, which has the shortest
234 "distance" in *RGB*nto the current color. In list context, you get
235 additionally the just mentioned distance as a second return value. This
236 method works almost identically as method "name", but guarantees a none
237 empty result, unless invoking a unusually empty color scheme.
238
239 All arguments work as mentioned above, only here is no "distance"
240 argument. The only difference is (due to the second return value),
241 multiple names (when requested) have to come in the form of an ARRAY as
242 the first return value.
243
244 my $name = $red_like->closest_name; # closest name in default scheme
245 my $name = $red_like->closest_name('HTML'); # closest HTML constant
246 ($red_name, $distance) = $red_like->closest_name( from => 'Pantone', all => 1 );
247
248 distance
249 Is a floating point number that measures the Euclidean distance between
250 two colors, which represent two points in a color space. One color is
251 the calling object itself and the second one has to be provided as
252 either the only argument or the named argument "to", which is the only
253 required one.
254
255 The "distance" is measured in *RGB* color space unless told otherwise by
256 the argument "in". Please use the *OKLAB* or *CIELUV* space, if you are
257 interested in getting a result that matches the human perception.
258
259 The third argument is named "select". It's useful if you want to regard
260 only certain dimensions (axis - long and short axis names are accepted).
261 For instance if you want to know only the difference in brightness
262 between two colors, you type "select => 'lightness'" or "select => 'l'".
263 This naturally works only if you did also choose *HSL* as a color space
264 or something similar that has a "lightness" axis like *LAB* or *OKLAB*.
265 The "select" argument accepts a string or an ARRAY with several axis
266 names, which can also repeat. For instance there is a formula to compute
267 distances in RGB that weights the squared value delta's: "$distance =
268 sqrt( 3 * delta_red**2 + 4 * delta_green**2 + 2 * delta_blue**2)". You
269 can recreate that formula by typing "select => [qw/ r r r g g g g b b/]"
270
271 The last argument is named "range", which can change the result
272 drasticly.
273
274 my $d = $blue->distance( 'lapisblue' ); # how close is blue to lapis?
275 $d = $blue->distance( to => 'airyblue', select => 'b'); # have they the same amount of blue?
276 $d = $color->distance( to => $c2, in => 'HSL', select => 'hue' ); # same hue?
277 $d = $color->distance( to => $c2, range => 'normal' ); # distance with values in 0 .. 1 range
278 $d = $color->distance( to => $c2, select => [qw/r g b b/]); # double the weight of blue value differences
279
280 SINGLE COLOR
281 These methods generate one new color object that is related to the
282 calling object (invocant). You might expect that methods like
283 "set_value" change the values of the invocant, but GTC objects are as
284 mentioned in the "DESCRIPTION" read only. That supports a more
285 functional programming style as well as method stacking like:
286
287 $color->add_value( saturation => 5)->invert->mix( to => 'green');
288
289 set_value
290 Creates a new GTC color object that shares some values with the current
291 one, but differs in others. The altered values are provided as absoltue
292 numbers. If the resulting color will be outside of the given color
293 space, the values will be clamped so it will become a regular color of
294 that space.
295
296 The axis of all supported color spaces have long and short names. For
297 instance *HSL* has *hue*, *sturation* and *lightness*. The short
298 equivalents are *h*, *s* and *l*. This method accepts these axis names
299 as named arguments and disregards if characters are written upper or
300 lower case. This method can not work, if you mix axis names from
301 different spaces or choose one axis more than once. One solvable issue
302 is when axis in different spaces have the same name. For instance *HSL*
303 and *HSV* have a *saturation* axis. To disambiguate you can add the
304 named argument "in".
305
306 my $blue = $black->set_value( blue => 255 ); # same as #0000ff
307 my $pale_blue = $blue->set_value( saturation => 50 ); # ->( s => 50) works too
308 my $color = $blue->set_value( saturation => 50, in => 'HSV' ); # previous was HSL
309
310 add_value
311 Creates a new GTC color object that shares some values with the current
312 one, but differs in others. The altered values are provided relative to
313 the current ones. The rest works as described in "set_value". This
314 method was mainly created to get lighter, darker or more saturated
315 colors by using it like:
316
317 my $blue = Graphics::Toolkit::Color->new('blue');
318 my $darkblue = $blue->add_value( Lightness => -25 ); # get a darker tone
319 my $blue2 = $blue->add_value( blue => 10 ); # bluer than blue ?
320 my $blue3 = $blue->add_value( l => 10, in => 'LAB' ); # lighter color according CIELAB
321
322 mix
323 Create a new GTC object, that has the average values between the calling
324 object and another color (or several colors). It accepts three named
325 arguments: "to", "amount" and "in", but only the first one is required.
326
327 "to" works like in other methods, with the exception that it also
328 accepts an ARRAY ref (square brackets) with several color definitions.
329
330 Per default *mix* computes a 50-50 (1:1) mix. In order to change that,
331 employ the "amount" argument, which is the weight the mixed in color(s)
332 get, counted in percentages. The remaining percentage to 100 is the
333 weight of the color, held by the caller object. This would be naturally
334 nothing, if the "amount" is greater than hundret, which is especially
335 something to consider, if mixing more than two colors. Then both "to"
336 and "amount" have to get an array of colors and respectively their
337 amounts (same order). Obviously both arrays MUST have the same length.
338 If the sum of amounts is greater than 100 the original color is ignored
339 but the weight ratios will be kept. You may actually give "amount" a
340 scalar value while mixing a list of colors. Then the amount is applied
341 to every color mentioned under the "to" argument. In this case you go
342 over the sum of 100% very quickly.
343
344 $blue->mix( 'silver'); # 50% silver, 50% blue
345 $blue->mix( to => 'silver', amount => 60 ); # 60% silver, 40% blue
346 $blue->mix( to => [qw/silver green/], amount => [10, 20]); # 10% silver, 20% green, 70% blue
347 $blue->mix( to => [qw/silver green/] ); # 50% silver, 50% green
348 $blue->mix( to => {H => 240, S =>100, L => 50}, in => 'RGB' ); # teal
349
350 invert
351 Computes the a new color object, where all values are inverted according
352 to the ranges of the chosen color space (see "in"). It takes only one
353 optional, positional argument, a space name.
354
355 my $black = $white->invert(); # to state the obvious
356 my $blue = $yellow->invert( 'LUV' ); # invert in LUV space
357 $yellow->invert( in => 'LUV' ); # would work too
358
359 COLOR SETS
360 construct several interrelated color objects at once.
361
362 complement
363 Creates a set of complementary colors (GTC objects), which will be
364 computed in *HSL* color space. The method accepts three optional, named
365 arguments: "steps" and "tilt" and "target". But if none are provided,
366 THE (one) complementary color will be produced.
367
368 One singular, positional argument defines the number of produced colors,
369 same as the named argument "steps" would have. If you want to get
370 'triadic' colors, choose 3 as an argument for "steps" - 4 would get you
371 the 'tetradic' colors, .... and so on. The given color is always the
372 last in the row of produced complementary colors.
373
374 If you need split-complementary colors, just use the "tilt" argument,
375 which defaults to zero. Without any tilt, complementary colors are
376 equally distanced dots on a horizontal circle around the vertical,
377 central column in *HSL* space. In other words: complementary colors have
378 all the same 'saturation' (distance from the column) and 'lightness'
379 (height). They differ only in 'hue' (position on the circle). The given
380 color and its (THE) complement sit on opposite sides of the circle. The
381 greater the "tilt" amount, the more these colors (minus the given one)
382 will move on the circle toward THE complement and vice versa. What is
383 traditionally meant by split-complementary colors you will get here with
384 a "tilt" factor of around 3.42 and three "steps" or a "tilt" of 1.585
385 and four "steps" (depending on if you need THE complement also in your
386 set).
387
388 To get an even greater variety of complementary colors, you can use
389 "target" argument and move around THE complement and thus shape the
390 circle in all three directions. "hue" (or "h") values move it circularly
391 "saturation" (or "s") move it away or negative values toward the central
392 column and "lightness" (or "l") move it up and down.
393
394 my @colors = $c->complement( 4 ); # 'tetradic' colors
395 my @colors = $c->complement( steps => 4, tilt => 4 ); # split-complementary colors
396 my @colors = $c->complement( steps => 3, tilt => { move => 2, target => {l => -10}} );
397 my @colors = $c->complement( steps => 3, tilt => { move => 2,
398 target => { h => 20, s=> -5, l => -10 } });
399
400 gradient
401 Creates a gradient (a list of color objects that build a transition)
402 between the current color held by the object and a second color,
403 provided by the named argument "to", which is required. Optionally "to"
404 accepts an ARRAY ref (square braces) with a list of colors in order to
405 create the most fancy, custom and nonlinear gradients.
406
407 Also required is the named argument "steps", which is the gradient
408 length or count of colors, which are part of this gradient. Included in
409 there are the start color (given by this object) and end color (given
410 with "to").
411
412 The optional, floating point valued argument "tilt" makes the gradient
413 skewed toward one or the other end. Default is zero, which results in a
414 linear, uniform transition between start and stop. Greater values of the
415 argument let the color change rate start small, steadily getting bigger.
416 Negative values work vice versa. The bigger the absolute numeric value
417 the bigger the effect. Please have in mind that values over 2 result is
418 a very strong tilt.
419
420 Optional is the named argument "in" (color space - details behind link).
421 Tip: use "oklab" and "cieluv" spaces for visually smooth gradients.
422
423 # we turn to grey
424 my @colors = $c->gradient( to => $grey, steps => 5);
425 # none linear gradient in HSL space :
426 @colors = $c1->gradient( to =>[14,10,222], steps => 10, tilt => 1, in => 'HSL' );
427 @colors = $c1->gradient( to =>['blue', 'brown', {h => 30, s => 44, l => 50}] );
428
429 cluster
430 Computes a set of colors that are all similar but not the same. The
431 method accepts three named arguments: "radius", "distance" and "in", of
432 which the first two are required.
433
434 The produced colors form a ball or cuboid in a color space around the
435 given color, depending on what the argument "radius" got. If it is a
436 single number, it will be a ball with the given radius. If it is an
437 ARRAY of values you get the a cuboid with the given dimensions.
438
439 The minimal distance between any two colors of a cluster is set by the
440 "minimal_distance" argument, which is computed the same way as the
441 method "distance", in has a short alias "min_d". In a cuboid shaped
442 cluster- the colors will form a cubic grid - inside the ball shaped
443 cluster they form a cuboctahedral grid, which is packed tighter, but
444 still obeys the minimal distance.
445
446 my @blues = $blue->cluster( radius => 4, minimal_distance => 0.3 );
447 my @c = $color->cluster( r => [2,2,3], min_d => 0.4, in => YUV );
448
449 ARGUMENTS
450 Some named arguments of the above listed methods reappear in several
451 methods. Thus they are explained here once. Please note that you must
452 NOT wrap the named args in curly braces (HASH ref).
453
454 in
455 The named argument *in* expects the name of a color space as listed
456 here. The default color space in this module is *RGB*. Depending on the
457 chosen space, the results of all methods can be very different, since
458 colors are arranged there very differently and have different distances
459 to each other. Some colors might not even exist in some spaces.
460
461 range
462 Every color space comes with range definitions for its values. For
463 instance *red*, *green* and *blue* in *RGB* go usually from zero to 255
464 (0..255). In order to change that, many methods accept the named
465 argument "range". When only one interger value provided, it changes the
466 upper bound on all three axis and as lower bound is assumed zero. Let's
467 say you need *RGB16* values with a range of 0 .. 65536, then you type
468 "range => 65536" or "range => 2**16".
469
470 If you provide an ARRAY ref you can change the upper bounds of all axis
471 individually and in order to change even the lower boundaries, use ARRAY
472 refs even inside that. For instance in "HSL" the "hue" is normally 0 ..
473 359 and the other two axis are 0 .. 100. In order to set "hue" to -100
474 .. 100 but keep the other two untouched you would have to insert: "range
475 => [[-100,100],100,100]".
476
477 to
478 This argument receives a second or target color. It may come in form of
479 another GTC object or a color definition that is acceptable to the
480 constructor. But it has to be a scalar (string or (HASH) reference), not
481 a value list or hash.
482
483 SEE ALSO
484 * Color::Scheme
485
486 * Graphics::ColorUtils
487
488 * Color::Fade
489
490 * Graphics::Color
491
492 * Graphics::ColorObject
493
494 * Color::Calc
495
496 * Convert::Color
497
498 * Color::Similarity
499
500 ACKNOWLEDGEMENT
501 These people contributed by providing patches, bug reports and useful
502 comments:
503
504 * Petr Pisar (ppisar)
505
506 * Slaven Rezic (srezic)
507
508 * Gabor Szabo (szabgab)
509
510 * Gene Boggs (GENE)
511
512 * Stefan Reddig (sreagle)
513
514 AUTHOR
515 Herbert Breunung, <[email protected]>
516
517 COPYRIGHT
518 Copyright 2022-2025 Herbert Breunung.
519
520 LICENSE
521 This program is free software; you can redistribute it and/or modify it
522 under the same terms as Perl itself.
523