-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (81 loc) · 1.92 KB
/
main.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"errors"
"flag"
"fmt"
"image"
"image/draw"
"image/jpeg"
"io"
"io/ioutil"
"os"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
)
func main() {
var drawValue, outputFilepath string
flag.StringVar(&drawValue, "d", "", "Draw value.")
flag.StringVar(&outputFilepath, "o", "", "Output filepath.")
flag.Parse()
f, err := os.Create(outputFilepath)
if err != nil {
fmt.Fprintf(os.Stderr, "%v.", err)
os.Exit(1)
}
if err := run(drawValue, f); err != nil {
fmt.Fprintf(os.Stderr, "%v.", err)
os.Exit(2)
}
}
func run(drawValue string, w io.Writer) error {
if drawValue == "" {
return errors.New("draw value is empty")
}
baseImg, err := getBaseImage()
if err != nil {
return err
}
fo, err := getFont()
if err != nil {
return err
}
drawImg := drawStringToImage(baseImg, fo, drawValue)
return jpeg.Encode(w, drawImg, &jpeg.Options{Quality: 100})
}
func getBaseImage() (image.Image, error) {
f, err := os.Open("static_files/images/src.jpg")
if err != nil {
return nil, err
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func getFont() (*truetype.Font, error) {
bs, err := ioutil.ReadFile("static_files/fonts/roboto-regular.ttf")
if err != nil {
return nil, err
}
fo, err := truetype.Parse(bs)
if err != nil {
return nil, err
}
return fo, nil
}
func drawStringToImage(baseImg image.Image, drawFont *truetype.Font, drawValue string) image.Image {
r := baseImg.Bounds()
drawImg := image.NewRGBA(image.Rect(0, 0, r.Dx(), r.Dy()))
draw.Draw(drawImg, drawImg.Bounds(), baseImg, r.Min, draw.Src)
d := &font.Drawer{Dst: drawImg, Src: image.Black}
d.Face = truetype.NewFace(drawFont, &truetype.Options{Size: 20, DPI: 350})
d.Dot = fixed.Point26_6{
X: (fixed.I(r.Dx()) - d.MeasureString(drawValue)) / 2,
Y: fixed.I(r.Dy() / 2),
}
d.DrawString(drawValue)
return d.Dst
}