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