-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.go
88 lines (70 loc) · 1.99 KB
/
image.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
package main
import (
"bufio"
"image"
"image/color"
"image/draw"
"image/png"
"io/ioutil"
"os"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
)
func GetDrawableFromImagePath(imagePath string) *image.RGBA {
file, err := os.Open(imagePath)
if err != nil {
panic(err)
}
reader := bufio.NewReader(file)
decodedImage, _, err := image.Decode(reader)
if err != nil {
panic(err)
}
decodedImageBounds := decodedImage.Bounds()
drawable := image.NewRGBA(image.Rect(0, 0, decodedImageBounds.Dx(), decodedImageBounds.Dy()))
draw.Draw(drawable, drawable.Bounds(), decodedImage, decodedImageBounds.Min, draw.Src)
return drawable
}
func LoadFontFromPath(fontPath string) *truetype.Font {
fontBytes, err := ioutil.ReadFile(fontPath)
if err != nil {
panic(err)
}
font, err := freetype.ParseFont(fontBytes)
if err != nil {
panic(err)
}
return font
}
func AddOverlayOnDrawable(drawable *image.RGBA, rectangle image.Rectangle, colour *color.RGBA, opacity *color.Alpha) {
draw.DrawMask(drawable, rectangle, &image.Uniform{colour}, image.ZP, &image.Uniform{opacity}, image.ZP, draw.Over)
}
func GetFreetypeContext(font *truetype.Font, dpi float64, fontSize float64, drawable *image.RGBA) *freetype.Context {
context := freetype.NewContext()
context.SetDPI(dpi)
context.SetFont(font)
context.SetFontSize(fontSize)
context.SetClip(drawable.Bounds())
context.SetDst(drawable)
context.SetSrc(image.Black)
return context
}
func WriteLinesOnRectangle(rectangle image.Rectangle, context *freetype.Context, lines []string, fontSize int, padding int) {
pointX := rectangle.Min.X + padding
pointY := rectangle.Min.Y + fontSize
for _, text := range lines {
labelPoint := freetype.Pt(pointX, pointY)
_, err := context.DrawString(text, labelPoint)
if err != nil {
panic(err)
}
pointY += fontSize + padding
}
}
func WriteToPngFile(filename string, drawable *image.RGBA) {
outFile, err := os.Create(filename)
if err != nil {
panic(err)
}
png.Encode(outFile, drawable)
}