-
Notifications
You must be signed in to change notification settings - Fork 0
/
croptop.go
64 lines (53 loc) · 1.21 KB
/
croptop.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
package croptop
import (
"image"
"io"
"math"
"github.com/disintegration/imaging"
)
// Image is an image
type Image struct {
img image.Image
width int
height int
offsetX int
offsetY int
}
// Decode reads the image from r
func Decode(r io.Reader) (*Image, error) {
img, err := imaging.Decode(r)
if err != nil {
return nil, err
}
return &Image{img: img}, nil
}
// Width sets the bounding box width
func (i *Image) Width(width float64) *Image {
i.width = int(math.Round(width))
return i
}
// Height sets the bounding box height
func (i *Image) Height(height float64) *Image {
i.height = int(math.Round(height))
return i
}
// OffsetX sets the x-coordinate offset
func (i *Image) OffsetX(x float64) *Image {
i.offsetX = int(math.Round(x))
return i
}
// OffsetY sets the y-coordinate offset
func (i *Image) OffsetY(y float64) *Image {
i.offsetY = int(math.Round(y))
return i
}
// Crop crops and returns a new image
func (i *Image) Crop() *Image {
rect := image.Rect(0, 0, i.width, i.height).
Add(image.Pt(i.offsetX, i.offsetY))
return &Image{img: imaging.Crop(i.img, rect)}
}
// Encode writes the image to w
func (i *Image) Encode(w io.Writer) error {
return imaging.Encode(w, i.img, imaging.JPEG)
}