-
Notifications
You must be signed in to change notification settings - Fork 8
/
crop.go
78 lines (71 loc) · 1.69 KB
/
crop.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
package imageutil
import (
"image"
"strings"
"golang.org/x/image/draw"
)
const (
AlignTop = "top"
AlignCenter = "center"
AlignBottom = "bottom"
AlignLeft = "left"
AlignRight = "right"
)
// Crop takes an image and crops it to the specified rectangle.
func Crop(src image.Image, retain image.Rectangle) image.Image {
new := image.NewRGBA(retain)
draw.Draw(new, new.Bounds(), src, retain.Min, draw.Over)
return new
}
// CropX crops an image by its width horizontally.
func CropX(src image.Image, width uint, align string) image.Image {
if int(width) >= src.Bounds().Dx() {
return src
}
var xMin int
switch strings.ToLower(strings.TrimSpace(align)) {
case AlignLeft:
xMin = src.Bounds().Min.X
case AlignRight:
xMin = src.Bounds().Max.X - int(width)
default:
xMin = (src.Bounds().Max.X - int(width)) / 2
}
return Crop(src, image.Rect(
xMin,
src.Bounds().Min.Y,
xMin+int(width),
src.Bounds().Max.Y))
}
// CropY crops an image by its height verticaly.
func CropY(src image.Image, height uint, align string) image.Image {
if int(height) >= src.Bounds().Dy() {
return src
}
var yMin int
switch strings.ToLower(strings.TrimSpace(align)) {
case AlignTop:
yMin = src.Bounds().Min.Y
case AlignBottom:
yMin = src.Bounds().Max.Y - int(height)
default:
yMin = (src.Bounds().Max.Y - int(height)) / 2
}
return Crop(src, image.Rect(
src.Bounds().Min.X,
yMin,
src.Bounds().Max.X,
yMin+int(height)))
}
func Square(src image.Image) image.Image {
width := src.Bounds().Dx()
height := src.Bounds().Dy()
switch {
case width == height:
return src
case width > height:
return CropX(src, uint(height), AlignCenter)
default:
return CropY(src, uint(width), AlignCenter)
}
}