This commit is contained in:
2025-12-14 06:04:57 +03:00
parent 2709034fc3
commit 02ece86303
23 changed files with 633 additions and 2 deletions

BIN
pkg/.hex_test.go.swp Normal file

Binary file not shown.

32
pkg/hex.go Normal file
View File

@@ -0,0 +1,32 @@
package imageutils
import (
"fmt"
"image/color"
"errors"
)
var ParseHexColorErr = errors.New("invalid length, must be 7 or 4")
func ParseHexColor(s string) (c color.RGBA, err error) {
c.A = 0xff
switch len(s) {
case 7:
_, err = fmt.Sscanf(s, "#%02x%02x%02x", &c.R, &c.G, &c.B)
case 4:
_, err = fmt.Sscanf(s, "#%1x%1x%1x", &c.R, &c.G, &c.B)
// Double the hex digits:
c.R *= 17
c.G *= 17
c.B *= 17
default:
err = ParseHexColorErr
}
return
}
func ColorToHex(c color.Color) string {
r, g, b, _ := color.NRGBAModel.Convert(c).RGBA()
return fmt.Sprintf("#%02x%02x%02x", byte(r), byte(g), byte(b))
}

47
pkg/hex_test.go Normal file
View File

@@ -0,0 +1,47 @@
package imageutils
import (
"fmt"
"image/png"
"os"
"path/filepath"
"testing"
)
// Returns path of first occured file
// with png extension in user's home directory.
func firstPNG(root string) (filename string,
err error) {
var fn filepath.WalkFunc = func(path string,
info os.FileInfo,
fileErr error) error {
if fileErr != nil {
return fileErr
}
if !info.IsDir() &&
filepath.Ext(path) == ".png" {
filename = path
return nil
}
return nil
}
err = filepath.Walk(root, fn)
return
}
func TestColorToHex(t *testing.T) {
root := os.Getenv("HOME")
path, err := firstPNG(root)
if err != nil {
t.Fatal(err)
}
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
img, err := png.Decode(f)
if err != nil {
t.Fatal(err)
}
fmt.Println(ColorToHex(img.At(0, 0)))
}