-
Notifications
You must be signed in to change notification settings - Fork 16
/
gentemplate.go
124 lines (96 loc) · 2.39 KB
/
gentemplate.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// gOCR - Template Generation Module
package main
import (
"bufio"
"image"
"image/color"
"image/draw"
"image/png"
"io/ioutil"
"os"
"sort"
"strconv"
"strings"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
)
const fontSize = 80
func getGlypBound(img image.Image) image.Rectangle {
white := color.RGBA{255, 255, 255, 255}
imgBound := img.Bounds()
yRange := make([]int, 0)
xRange := make([]int, 0)
for y := 0; y < imgBound.Max.Y; y++ {
for x := 0; x < imgBound.Max.X; x++ {
if img.At(x, y) != white {
yRange = append(yRange, y)
xRange = append(xRange, x)
}
}
}
sort.Ints(yRange)
sort.Ints(xRange)
return image.Rectangle{image.Point{xRange[0], yRange[0]}, image.Point{xRange[len(xRange)-1] + 1, yRange[len(yRange)-1] + 1}}
}
// Write character to the file
func writeGlyp(str string, count int, font *truetype.Font) {
background := image.NewRGBA(image.Rect(0, 0, fontSize*3/2, fontSize*3/2))
draw.Draw(background, background.Bounds(), image.NewUniform(color.RGBA{255, 255, 255, 255}), image.ZP, draw.Src)
// Set context value
ctx := freetype.NewContext()
ctx.SetDPI(72)
ctx.SetFont(font)
ctx.SetFontSize(fontSize)
ctx.SetClip(background.Bounds())
ctx.SetDst(background)
ctx.SetSrc(image.NewUniform(color.RGBA{0, 0, 0, 255}))
// Draw the text to the background
_, err := ctx.DrawString(str, freetype.Pt(fontSize/2, fontSize))
if err != nil {
panic(err)
}
count++
filename := strconv.Itoa(count) + ".png"
glypBound := getGlypBound(background)
// Save
outFile, err := os.Create(templateDir + filename)
if err != nil {
panic(err)
}
buff := bufio.NewWriter(outFile)
err = png.Encode(buff, background.SubImage(glypBound))
if err != nil {
panic(err)
}
// flush everything out to file
err = buff.Flush()
if err != nil {
panic(err)
}
outFile.Close()
}
// ReadCharList - Read character list
func ReadCharList(file string) []string {
b, err := ioutil.ReadFile(file) // just pass the file name
if err != nil {
panic(err)
}
return strings.Split(string(b), " ")
}
// GenTemplate - Generate Template file
func GenTemplate(charList []string, fontFile, templateDir string) {
fontBytes, err := ioutil.ReadFile(fontFile)
if err != nil {
panic(err)
}
font, err := freetype.ParseFont(fontBytes)
if err != nil {
panic(err)
}
count := 0
// Each glyps
for _, str := range charList {
writeGlyp(str, count, font)
count++
}
}