-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
63 lines (53 loc) · 1.48 KB
/
slice.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
package tiletools
import (
"fmt"
"image"
"image/draw"
"math"
)
// SliceImage slices input imgFile into smaller tiles
func SliceImage(imgFile string, tileWidth int, tileHeight int, force bool) ([]image.Image, error) {
var slices []image.Image
img, _, err := LoadImage(imgFile)
if err != nil {
return nil, err
}
b := img.Bounds()
imgWidth := b.Max.X
imgHeight := b.Max.Y
cols := float64(imgWidth) / float64(tileWidth)
rows := float64(imgHeight) / float64(tileHeight)
if !force && cols != math.Floor(cols) {
return nil, fmt.Errorf("input image width %d is not evenly divisible by tile width %d", imgWidth, tileWidth)
}
if !force && rows != math.Floor(rows) {
return nil, fmt.Errorf("input image height %d is not evenly divisible by tile height %d", imgHeight, tileHeight)
}
for row := 0; row < int(rows); row++ {
for col := 0; col < int(cols); col++ {
x0 := col * tileWidth
y0 := row * tileHeight
x1 := (col + 1) * tileWidth
y1 := (row + 1) * tileHeight
sr := image.Rect(x0, y0, x1, y1)
dst := image.NewRGBA(image.Rect(0, 0, tileWidth, tileHeight))
r := sr.Sub(sr.Min).Add(image.Point{0, 0})
draw.Draw(dst, r, img, sr.Min, draw.Src)
slices = append(slices, dst)
}
}
return slices, nil
}
// is this an empty tile?
func isOnlyTransparent(img *image.RGBA) bool {
b := img.Bounds()
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
_, _, _, a := img.At(x, y).RGBA()
if a > 0 {
return false
}
}
}
return true
}