-
Notifications
You must be signed in to change notification settings - Fork 0
/
imgScaler.go
67 lines (57 loc) · 1.5 KB
/
imgScaler.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
package img
import (
"fmt"
"path"
"path/filepath"
"strings"
)
func NewImgScaler(sourceFilePath, destinationDirPath string) *ImgScaler {
if !strings.HasSuffix(destinationDirPath, "/") {
destinationDirPath += "/"
}
i := new(ImgScaler)
i.sourceFilePath = sourceFilePath
i.destinationDirPath = destinationDirPath
return i
}
type ImgScaler struct {
maxSizes []int
sourceFilePath string
destinationDirPath string
destPaths []string
}
func (i *ImgScaler) PrepareResizeTo(widths ...int) []string {
i.maxSizes = widths
return i.getPaths()
}
func (i *ImgScaler) Resize() {
ic := newImageContainer(i.sourceFilePath)
for _, ms := range i.maxSizes {
ic.resizeToAndSaveAs(i.getPathFor(ms), ms)
}
}
func (i *ImgScaler) ResizeAndCrop() {
ic := newImageContainer(i.sourceFilePath)
for _, ms := range i.maxSizes {
ic.resizeAndCropToAndSaveAs(i.getPathFor(ms), ms)
}
}
func (i *ImgScaler) getPaths() []string {
pths := []string{}
for _, ms := range i.maxSizes {
pths = append(pths, i.getPathFor(ms))
}
return pths
}
func (i *ImgScaler) getPathFor(ms int) string {
fileExtension := filepath.Ext(i.sourceFileName())
basename := strings.TrimSuffix(i.sourceFileName(), fileExtension)
newFilename := basename + i.getSizeTagForFilename(ms) + fileExtension
return path.Join(i.destinationDirPath, newFilename)
}
func (i *ImgScaler) getSizeTagForFilename(w int) string {
return fmt.Sprintf("-w%d", w)
}
func (i *ImgScaler) sourceFileName() string {
return filepath.Base(i.sourceFilePath)
}