-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
100 lines (84 loc) · 2.2 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package color_thief
import (
"color-thief/helper"
"color-thief/wsm"
"color-thief/wu"
"errors"
"image"
"image/color"
"image/png"
"os"
)
// GetColorFromFile return the base color from the image file
func GetColorFromFile(imgPath string) (color.Color, error) {
colors, err := GetPaletteFromFile(imgPath, 10, 0)
if err != nil {
return color.RGBA{}, err
}
return colors[0], nil
}
// GetColor return the base color from the image
func GetColor(img image.Image, numColors, functionType int) (color.Color, error) {
colors, err := GetPalette(img, numColors, functionType)
if err != nil {
return color.RGBA{}, err
}
return colors[0], nil
}
// GetPaletteFromFile return cluster similar colors from the image file
func GetPaletteFromFile(imgPath string, numColors, functionType int) ([]color.Color, error) {
var img image.Image
var err error
// load image
img, err = helper.ReadImage(imgPath)
if err != nil {
return nil, err
}
return GetPalette(img, numColors, functionType)
}
// GetPalette return cluster similar colors by the median cut algorithm
func GetPalette(img image.Image, numColors, functionType int) ([]color.Color, error) {
var palette, pixels [][3]int
var colors []color.Color
if numColors < 1 {
return nil, errors.New("number of colors should be greater than 0")
}
pixels = helper.SubsamplingPixelsFromImage(img)
switch functionType {
case 0:
palette = wu.QuantWu(pixels, numColors)
break
case 1:
palette = wsm.WSM(pixels, numColors)
break
default:
return nil, errors.New("function type should be either 0 or 1")
}
colors = make([]color.Color, len(palette))
for i, v := range palette {
colors[i] = helper.Color(v)
}
return colors, nil
}
func PrintColor(colors []color.Color, filename string) error {
imgWidth := 100 * len(colors)
imgHeight := 200
if imgWidth == 0 {
return errors.New("colors empty")
}
palettes := image.NewPaletted(image.Rect(0, 0, imgWidth, imgHeight), colors)
for x := 0; x < imgWidth; x++ {
idx := x / 100
for y := 0; y < imgHeight; y++ {
palettes.SetColorIndex(x, y, uint8(idx))
}
}
file, err := os.Create(filename)
if err != nil {
return err
}
if err = png.Encode(file, palettes); err != nil {
return err
}
return file.Close()
}