-
Notifications
You must be signed in to change notification settings - Fork 3
/
imageutil.go
46 lines (43 loc) · 935 Bytes
/
imageutil.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
package main
import (
"fmt"
)
func Downsample(img *Image, factor int) (*Image, error) {
width := img.Width
height := img.Height
if width%factor != 0 || height%factor != 0 {
return nil, fmt.Errorf("bad image dimensions for supersampling rate %d", factor)
}
dWidth := width / factor
dHeight := height / factor
dImg := NewImage(dWidth, dHeight)
colors := []Color{}
for dx := 0; dx < dWidth; dx++ {
for dy := 0; dy < dHeight; dy++ {
startX := dx * factor
startY := dy * factor
colors = colors[:0]
for x := startX; x < startX+factor; x++ {
for y := startY; y < startY+factor; y++ {
colors = append(colors, img.At(x, y))
}
}
dImg.Set(dx, dy, ColorAvg(colors))
}
}
return dImg, nil
}
func ColorAvg(colors []Color) Color {
var r, g, b float64
for _, c := range colors {
r += c.R
g += c.G
b += c.B
}
n := float64(len(colors))
return Color{
R: r / n,
G: g / n,
B: b / n,
}
}