github.com/linchen2chris/hugo@v0.0.0-20230307053224-cec209389705/resources/images/color.go (about) 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 "strings" 21 ) 22 23 // AddColorToPalette adds c as the first color in p if not already there. 24 // Note that it does no additional checks, so callers must make sure 25 // that the palette is valid for the relevant format. 26 func AddColorToPalette(c color.Color, p color.Palette) color.Palette { 27 var found bool 28 for _, cc := range p { 29 if c == cc { 30 found = true 31 break 32 } 33 } 34 35 if !found { 36 p = append(color.Palette{c}, p...) 37 } 38 39 return p 40 } 41 42 // ReplaceColorInPalette will replace the color in palette p closest to c in Euclidean 43 // R,G,B,A space with c. 44 func ReplaceColorInPalette(c color.Color, p color.Palette) { 45 p[p.Index(c)] = c 46 } 47 48 // ColorToHexString converts a color to a hex string. 49 func ColorToHexString(c color.Color) string { 50 r, g, b, a := c.RGBA() 51 rgba := color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)} 52 return fmt.Sprintf("#%.2x%.2x%.2x", rgba.R, rgba.G, rgba.B) 53 54 } 55 56 func hexStringToColor(s string) (color.Color, error) { 57 s = strings.TrimPrefix(s, "#") 58 59 if len(s) != 3 && len(s) != 6 { 60 return nil, fmt.Errorf("invalid color code: %q", s) 61 } 62 63 s = strings.ToLower(s) 64 65 if len(s) == 3 { 66 var v string 67 for _, r := range s { 68 v += string(r) + string(r) 69 } 70 s = v 71 } 72 73 // Standard colors. 74 if s == "ffffff" { 75 return color.White, nil 76 } 77 78 if s == "000000" { 79 return color.Black, nil 80 } 81 82 // Set Alfa to white. 83 s += "ff" 84 85 b, err := hex.DecodeString(s) 86 if err != nil { 87 return nil, err 88 } 89 90 return color.RGBA{b[0], b[1], b[2], b[3]}, nil 91 }