color.go (1887B)
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 func hexStringToColor(s string) (color.Color, error) { 49 s = strings.TrimPrefix(s, "#") 50 51 if len(s) != 3 && len(s) != 6 { 52 return nil, fmt.Errorf("invalid color code: %q", s) 53 } 54 55 s = strings.ToLower(s) 56 57 if len(s) == 3 { 58 var v string 59 for _, r := range s { 60 v += string(r) + string(r) 61 } 62 s = v 63 } 64 65 // Standard colors. 66 if s == "ffffff" { 67 return color.White, nil 68 } 69 70 if s == "000000" { 71 return color.Black, nil 72 } 73 74 // Set Alfa to white. 75 s += "ff" 76 77 b, err := hex.DecodeString(s) 78 if err != nil { 79 return nil, err 80 } 81 82 return color.RGBA{b[0], b[1], b[2], b[3]}, nil 83 }