-
Notifications
You must be signed in to change notification settings - Fork 0
/
display.go
100 lines (89 loc) · 2.71 KB
/
display.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
package unicornsignage
import (
"bytes"
"embed"
"image"
"image/color"
"strconv"
owm "github.com/briandowns/openweathermap"
"github.com/disintegration/imaging"
"github.com/fogleman/gg"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
)
func ImageFromText(text string, fontBytes []byte, x int, fontsize int) (outimg image.Image, err error) {
newImage := image.NewNRGBA(image.Rect(0, 0, 16, 16))
labelImage, err := addText(newImage, -x, 12, text, fontsize, fontBytes)
if err != nil {
return nil, err
}
// rotate the image by 90 degrees
dstImage := imaging.Rotate90(labelImage)
return dstImage, nil
}
func GetWeatherImageFromAPI(apikey string, location string, imageLocation embed.FS) (outImage image.Image, err error) {
w, err := owm.NewCurrent("C", "EN", apikey)
if err != nil {
return nil, err
}
err = w.CurrentByName(location)
if err != nil {
return nil, err
}
id := w.Weather[0].ID
isNight := w.Weather[0].Icon[len(w.Weather[0].Icon)-1:] == "n"
existingImageFile, err := imageLocation.ReadFile("images/" + "weatherImages/" + strconv.Itoa(id) + ".png")
if err != nil {
if isNight {
existingImageFile, err = imageLocation.ReadFile("images/" + "weatherImages/" + strconv.Itoa(id) + "n" + ".png")
if err != nil {
return nil, err
}
} else {
existingImageFile, err = imageLocation.ReadFile("images/" + "weatherImages/" + strconv.Itoa(id) + "d" + ".png")
if err != nil {
return nil, err
}
}
}
existingImage, _, err := image.Decode(bytes.NewReader(existingImageFile))
if err != nil {
return nil, err
}
return existingImage, nil
}
func RotateImage90(img image.Image) (outimage image.Image, err error) {
// rotate the image by 90 degrees
dstImage := imaging.Rotate(img, 90, color.Black)
return dstImage, nil
}
func loadFontFaceReader(fontBytes []byte, points float64) (font.Face, error) {
f, err := truetype.Parse(fontBytes)
if err != nil {
return nil, err
}
face := truetype.NewFace(f, &truetype.Options{
Size: points,
// Hinting: font.HintingFull,
})
return face, nil
}
func addText(img image.Image, x, y int, label string, size int, fontBytes []byte) (outimage image.Image, err error) {
var w = img.Bounds().Dx()
var h = img.Bounds().Dy()
dc := gg.NewContext(w, h)
// Text color - white
dc.SetRGB(1, 1, 1)
face, err := loadFontFaceReader(fontBytes, float64(size))
if err != nil {
return nil, err
}
dc.SetFontFace(face)
// Draw the background
dc.DrawImage(img, 0, 0)
// Draw text at position - anchor on the top left corner of the text
dc.DrawStringAnchored(label, float64(x), float64(y), 0, 0)
dc.Clip()
outimage = dc.Image()
return outimage, nil
}