forked from joonhoj/mogrify-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbounds.go
76 lines (63 loc) · 1.86 KB
/
bounds.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
package mogrify
import (
"fmt"
"math"
"regexp"
"strconv"
)
var boundFinder = regexp.MustCompile("([0-9]*)x([0-9]*)")
// Bounds of an image.
type Bounds struct {
Width, Height int
}
// BoundsFromString creates a Bounds from strings of the form:
// "100x150" -> Width 100, Height 150
// "x150" -> Width 0, Height 150
// "100x" -> Width 100, Height 0
// "x" -> Width 0, Height 0
// "no match" -> error
func BoundsFromString(bounds string) (*Bounds, error) {
dimensions := boundFinder.FindStringSubmatch(bounds)
if len(dimensions) != 3 {
return nil, fmt.Errorf("malformed bound string")
}
atoiOrZero := func(str string) int {
if str == "" {
return 0
}
val, _ := strconv.Atoi(str)
return val
}
return &Bounds{
Width: atoiOrZero(dimensions[1]),
Height: atoiOrZero(dimensions[2]),
}, nil
}
// ScaleProportionally the bounds to the smallest side.
func (b Bounds) ScaleProportionally(targetWidth, targetHeight int) Bounds {
scalex := float64(targetWidth) / float64(b.Width)
scaley := float64(targetHeight) / float64(b.Height)
scale := math.Min(scalex, scaley)
return Bounds{
Width: int(math.Floor(float64(b.Width) * scale)),
Height: int(math.Floor(float64(b.Height) * scale)),
}
}
// ShrinkProportionally the bounds only if both sides are larger than
// the target.
func (b Bounds) ShrinkProportionally(targetWidth, targetHeight int) Bounds {
// Make sure there is work to be done
if b.Width < targetWidth || b.Height < targetHeight {
return b
}
return b.ScaleProportionally(targetWidth, targetHeight)
}
// GrowProportionally the bounds only if both sides are smaller than
// the target.
func (b Bounds) GrowProportionally(targetWidth, targetHeight int) Bounds {
// Make sure there is work to be done
if b.Width > targetWidth || b.Height > targetHeight {
return b
}
return b.ScaleProportionally(targetWidth, targetHeight)
}