Debian Codegraph @

resources/images/color.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package images
15
16 import (
17 "encoding/hex"
18 "fmt"
19 "image/color"
20 "math"
21 "slices"
22 "strings"
23
24 "github.com/gohugoio/hugo/common/hstrings"
25 )
26
27 type colorGoProvider interface {
28 ColorGo() color.Color
29 }
30
31 type Color struct {
32 // The color.
33 color color.Color
34
35 // The color prefixed with a #.
36 hex string
37
38 // The relative luminance of the color.
39 luminance float64
40 }
41
42 // Luminance as defined by w3.org.
43 // See https://www.w3.org/TR/WCAG21/#dfn-relative-luminance
44 func (c Color) Luminance() float64 {
45 return c.luminance
46 }
47
48 // ColorGo returns the color as a color.Color.
49 // For internal use only.
50 func (c Color) ColorGo() color.Color {
51 return c.color
52 }
53
54 // ColorHex returns the color as a hex string prefixed with a #.
55 func (c Color) ColorHex() string {
56 return c.hex
57 }
58
59 // String returns the color as a hex string prefixed with a #.
60 func (c Color) String() string {
61 return c.hex
62 }
63
64 // For hashstructure. This struct is used in template func options
65 // that needs to be able to hash a Color.
66 // For internal use only.
67 func (c Color) Key() string {
68 return c.hex
69 }
70
71 func (c *Color) init() error {
72 // Normalize to the canonical non-premultiplied form so that equal colors
73 // compare equal whether they came from a hex string or from image pixels.
74 nrgba := color.NRGBAModel.Convert(c.color).(color.NRGBA)
75 c.color = nrgba
76 c.hex = ColorGoToHexString(nrgba)
77 c.luminance = 0.2126*c.toSRGB(nrgba.R) + 0.7152*c.toSRGB(nrgba.G) + 0.0722*c.toSRGB(nrgba.B)
78 return nil
79 }
80
81 func (c Color) toSRGB(i uint8) float64 {
82 v := float64(i) / 255
83 if v <= 0.04045 {
84 return v / 12.92
85 } else {
86 return math.Pow((v+0.055)/1.055, 2.4)
87 }
88 }
89
90 // AddColorToPalette adds c as the first color in p if not already there.
91 // Note that it does no additional checks, so callers must make sure
92 // that the palette is valid for the relevant format.
93 func AddColorToPalette(c color.Color, p color.Palette) color.Palette {
94 // Compare color values rather than interface values, so that e.g. a
95 // color.NRGBA is found even if the palette holds it as a color.RGBA.
96 cr, cg, cb, ca := c.RGBA()
97 found := slices.ContainsFunc(p, func(v color.Color) bool {
98 vr, vg, vb, va := v.RGBA()
99 return cr == vr && cg == vg && cb == vb && ca == va
100 })
101
102 if !found {
103 p = append(color.Palette{c}, p...)
104 }
105
106 return p
107 }
108
109 // ReplaceColorInPalette will replace the color in palette p closest to c in Euclidean
110 // R,G,B,A space with c.
111 func ReplaceColorInPalette(c color.Color, p color.Palette) {
112 p[p.Index(c)] = c
113 }
114
115 // ColorGoToHexString converts a color.Color to a hex string.
116 func ColorGoToHexString(c color.Color) string {
117 // Hex notation is not alpha-premultiplied, so convert via NRGBA to
118 // un-premultiply the color components of any transparent color.
119 nrgba := color.NRGBAModel.Convert(c).(color.NRGBA)
120 if nrgba.A == 0xff {
121 return fmt.Sprintf("#%.2x%.2x%.2x", nrgba.R, nrgba.G, nrgba.B)
122 }
123 return fmt.Sprintf("#%.2x%.2x%.2x%.2x", nrgba.R, nrgba.G, nrgba.B, nrgba.A)
124 }
125
126 // ColorGoToColor converts a color.Color to a Color.
127 func ColorGoToColor(c color.Color) Color {
128 cc := Color{color: c}
129 if err := cc.init(); err != nil {
130 panic(err)
131 }
132 return cc
133 }
134
135 func hexStringToColor(s string) Color {
136 c, err := hexStringToColorGo(s)
137 if err != nil {
138 panic(err)
139 }
140 return ColorGoToColor(c)
141 }
142
143 // HexStringsToColors converts a slice of hex strings to a slice of Colors.
144 func HexStringsToColors(s ...string) []Color {
145 var colors []Color
146 for _, v := range s {
147 colors = append(colors, hexStringToColor(v))
148 }
149 return colors
150 }
151
152 func toColorGo(v any) (color.Color, bool, error) {
153 switch vv := v.(type) {
154 case colorGoProvider:
155 return vv.ColorGo(), true, nil
156 default:
157 s, ok := hstrings.ToString(v)
158 if !ok {
159 return nil, false, nil
160 }
161 c, err := hexStringToColorGo(s)
162 if err != nil {
163 return nil, false, err
164 }
165 return c, true, nil
166 }
167 }
168
169 func hexStringToColorGo(s string) (color.Color, error) {
170 s = strings.TrimPrefix(s, "#")
171
172 if len(s) != 3 && len(s) != 4 && len(s) != 6 && len(s) != 8 {
173 return nil, fmt.Errorf("invalid color code: %q", s)
174 }
175
176 s = strings.ToLower(s)
177
178 if len(s) == 3 || len(s) == 4 {
179 var v strings.Builder
180 for _, r := range s {
181 v.WriteString(string(r) + string(r))
182 }
183 s = v.String()
184 }
185
186 // Standard colors.
187 if s == "ffffff" {
188 return color.White, nil
189 }
190
191 if s == "000000" {
192 return color.Black, nil
193 }
194
195 // Set Alfa to white.
196 if len(s) == 6 {
197 s += "ff"
198 }
199
200 b, err := hex.DecodeString(s)
201 if err != nil {
202 return nil, err
203 }
204
205 // Hex notation is not alpha-premultiplied, so this must be a color.NRGBA;
206 // as a color.RGBA any transparent color would be invalid (component > alpha)
207 // and corrupted when drawn onto an alpha-premultiplied image. See issue 12536.
208 return color.NRGBA{b[0], b[1], b[2], b[3]}, nil
209 }