-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrop.go
More file actions
76 lines (65 loc) · 1.63 KB
/
Copy pathcrop.go
File metadata and controls
76 lines (65 loc) · 1.63 KB
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
package pixo
import (
"image"
"image/draw"
)
// Crop crops img to the specified rectangle.
func Crop(img image.Image, rect image.Rectangle) *image.NRGBA {
if img == nil {
return &image.NRGBA{}
}
rect = rect.Intersect(img.Bounds())
if rect.Empty() {
return &image.NRGBA{}
}
dst := image.NewNRGBA(image.Rect(0, 0, rect.Dx(), rect.Dy()))
draw.Draw(dst, dst.Bounds(), img, rect.Min, draw.Src)
return dst
}
// CropAnchor crops img to the specified dimensions using the anchor point.
func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA {
if img == nil {
return &image.NRGBA{}
}
srcBounds := img.Bounds()
srcW := srcBounds.Dx()
srcH := srcBounds.Dy()
if width <= 0 || height <= 0 || srcW == 0 || srcH == 0 {
return &image.NRGBA{}
}
if width > srcW {
width = srcW
}
if height > srcH {
height = srcH
}
var x, y int
switch anchor {
case TopLeft:
x, y = 0, 0
case Top:
x, y = (srcW-width)/2, 0
case TopRight:
x, y = srcW-width, 0
case Left:
x, y = 0, (srcH-height)/2
case Center:
x, y = (srcW-width)/2, (srcH-height)/2
case Right:
x, y = srcW-width, (srcH-height)/2
case BottomLeft:
x, y = 0, srcH-height
case Bottom:
x, y = (srcW-width)/2, srcH-height
case BottomRight:
x, y = srcW-width, srcH-height
default:
x, y = (srcW-width)/2, (srcH-height)/2
}
rect := image.Rect(x+srcBounds.Min.X, y+srcBounds.Min.Y, x+srcBounds.Min.X+width, y+srcBounds.Min.Y+height)
return Crop(img, rect)
}
// CropCenter crops img to the specified dimensions from the center.
func CropCenter(img image.Image, width, height int) *image.NRGBA {
return CropAnchor(img, width, height, Center)
}