/
transform.go
80 lines (61 loc) · 1.45 KB
/
transform.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
79
80
package main
import (
"bytes"
"fmt"
"github.com/disintegration/imaging"
"image"
"image/png"
"io"
"runtime"
)
const (
RATIO = 0.18672199170124
)
func MakeImages(rect *image.Rectangle, file io.Reader) ([]*bytes.Buffer, error) {
runtime.GOMAXPROCS(runtime.NumCPU())
ar := aspectRatio(rect)
if ar < RATIO {
return nil, fmt.Errorf("makeImages: aspect ratio is too small")
} else if ar > RATIO {
cropRatio(rect)
}
img, _, err := image.Decode(file)
if err != nil {
return nil, err
}
img = imaging.Clone(img)
top := rect.Min.Y
square := squareHeight(rect)
space := spaceHeight(rect)
buffers := make([]*bytes.Buffer, 5, 5)
for i := 0; i < 5; i++ {
new_rect := image.Rect(rect.Min.X, top, rect.Max.X, top+square)
new_img := imaging.Crop(img, new_rect)
buffers[i] = bytes.NewBuffer(make([]byte, 0))
err = png.Encode(buffers[i], new_img)
if err != nil {
panic(err)
}
top = top + square + space
}
return buffers, nil
}
func squareHeight(rect *image.Rectangle) int {
return int(float64(rect.Dy()) * RATIO)
}
func spaceHeight(rect *image.Rectangle) int {
return int(float64(rect.Dy()) * 0.01659751037344)
}
func aspectRatio(rect *image.Rectangle) float64 {
return float64(rect.Dx()) / float64(rect.Dy())
}
func cropRatio(rect *image.Rectangle) {
if aspectRatio(rect) <= RATIO {
return
}
ideal := int(float64(rect.Dy()) * RATIO)
trim := (rect.Dx() - ideal) / 2
// Make corrections
rect.Min.X += trim
rect.Max.X -= trim
}