-
Notifications
You must be signed in to change notification settings - Fork 0
/
crop_image.go
82 lines (71 loc) · 1.51 KB
/
crop_image.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
package counters
import (
"image"
"github.com/disintegration/imaging"
)
func CropToContent(i image.Image) image.Image {
bounds := i.Bounds()
max := bounds.Max
min := bounds.Min
topLimit := min.Y
leftLimit := max.X
lowerLimit := 0
rightLimit := 0
var alpha uint32
topLimitLoop:
for row := 0; row < max.Y; row++ {
for column := 0; column < max.X; column++ {
_, _, _, alpha = i.At(column, row).RGBA()
//If color is found
if alpha > 0 {
if topLimit == 0 {
if topLimit > 0 {
topLimit = row - 1
} else {
topLimit = row
}
}
break topLimitLoop
}
}
}
leftLimitLoop:
for column := 0; column < max.X; column++ {
for row := topLimit; row < max.Y; row++ {
_, _, _, alpha = i.At(column, row).RGBA()
//If color is found
if alpha > 0 {
leftLimit = column
break leftLimitLoop
}
}
}
rightLimitLoop:
for column := max.X; column >= leftLimit; column-- {
for row := topLimit; row < max.Y; row++ {
_, _, _, alpha = i.At(column, row).RGBA()
//If color is found
if alpha > 0 {
rightLimit = column + 1
break rightLimitLoop
}
}
}
lowerLimitLoop:
for row := max.Y; row >= topLimit; row-- {
for column := leftLimit; column < rightLimit; column++ {
_, _, _, alpha = i.At(column, row).RGBA()
//If color is found
if alpha > 0 {
lowerLimit = row + 1
break lowerLimitLoop
}
}
}
rect := image.Rect(leftLimit, topLimit, rightLimit, lowerLimit)
if rect == bounds {
return i
}
newImg := imaging.Crop(i, rect)
return newImg
}