-
Notifications
You must be signed in to change notification settings - Fork 3
/
text.go
130 lines (111 loc) · 2.26 KB
/
text.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
125
126
127
128
129
130
// text drawer
package draw
import (
"github.com/golang/freetype"
"image"
"image/draw"
"io/ioutil"
"log"
"unicode/utf8"
)
// Text render text with given font
func Text(text string, fontPath string) *image.Gray {
fontBytes, err := ioutil.ReadFile(fontPath)
if err != nil {
log.Fatal(err)
}
font, err := freetype.ParseFont(fontBytes)
if err != nil {
log.Fatal(err)
}
fontSize := 20.
c := freetype.NewContext()
c.SetDPI(96)
c.SetFont(font)
c.SetFontSize(fontSize)
height := int(c.PointToFixed(fontSize) >> 6)
width := utf8.RuneCountInString(text) * height // still need to crop
fg, bg := image.Black, image.White
canvas := image.NewGray(image.Rect(0, 0, width, height+5))
draw.Draw(canvas, canvas.Bounds(), bg, image.Point{}, draw.Src)
c.SetClip(canvas.Bounds())
c.SetDst(canvas)
c.SetSrc(fg)
_, err = c.DrawString(text, freetype.Pt(0, height))
if err != nil {
log.Fatal(err)
}
return canvas
}
// Clip will clip text image to right size
// for golang doesn't have any direct way to get render string size
func Clip(img *image.Gray) image.Image {
bound := img.Bounds().Max
X, Y := bound.X, bound.Y
var rowPixels [][]bool
for y := 0; y < Y; y++ {
var row []bool
for x := 0; x < X; x++ {
row = append(row, img.GrayAt(x, y).Y == 255)
}
rowPixels = append(rowPixels, row)
}
upBorder, upBoarderFound := 0, false
downBorder := 0
for y := 0; y < Y; y++ {
isBlank := true
for x := 0; x < X; x++ {
if !rowPixels[y][x] {
isBlank = false
}
}
if !upBoarderFound && isBlank {
upBorder++
}
if !isBlank {
upBoarderFound = true
}
if downBorder == 0 && isBlank && upBoarderFound {
downBorder = y
}
}
leftBorder := 0
rightBorder := X
for x := 0; x < X; x++ {
isBlank := true
for y := 0; y < Y; y++ {
if !rowPixels[y][x] {
isBlank = false
}
}
if !isBlank {
break
}
if isBlank {
leftBorder++
}
}
for x := X - 1; x >= 0; x-- {
isBlank := true
for y := 0; y < Y; y++ {
if !rowPixels[y][x] {
isBlank = false
}
}
if isBlank {
rightBorder--
}
if !isBlank {
break
}
}
// possible issue
if leftBorder > 0 {
leftBorder -= 1
}
if downBorder <= 0 {
downBorder = Y
}
rightBorder += 1
return img.SubImage(image.Rect(leftBorder, upBorder, rightBorder, downBorder))
}