Repository navigation
Expand file tree
/
Copy pathicon.go
More file actions
70 lines (59 loc) · 1.63 KB
/
Copy pathicon.go
File metadata and controls
70 lines (59 loc) · 1.63 KB
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
package main
import (
"crypto/md5"
"image/color"
"image/png"
"net/http"
"regexp"
"github.com/fogleman/gg"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font/gofont/goregular"
)
func handleIcon(w http.ResponseWriter, r *http.Request) {
stop := r.URL.Query().Get("stop")
if stop == "" {
http.Error(w, "stop parameter missing", http.StatusBadRequest)
return
}
matched, err := regexp.MatchString(`\d\d\d\d\d`, stop)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !matched {
http.Error(w, "not 5 digits", http.StatusBadRequest)
return
}
hash := md5.Sum([]byte(stop))
bgColor := color.RGBA{R: hash[0], G: hash[1], B: hash[2], A: 255}
const S = 200
maxWidth := float64(S) - 20
dc := gg.NewContext(S, S)
dc.SetColor(bgColor)
dc.Clear()
font, err := truetype.Parse(goregular.TTF)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
face := truetype.NewFace(font, &truetype.Options{Size: 48})
dc.SetFontFace(face)
// A dark outline preserves the white digits on pale stop colours.
const outline = 2
dc.SetRGB(0.12, 0.12, 0.12)
for dy := -outline; dy <= outline; dy++ {
for dx := -outline; dx <= outline; dx++ {
if dx*dx+dy*dy <= outline*outline {
dc.DrawStringWrapped(stop, S/2+float64(dx), S/2+float64(dy), 0.5, 0.5, maxWidth, 1.5, gg.AlignCenter)
}
}
}
dc.SetRGB(1, 1, 1)
dc.DrawStringWrapped(stop, S/2, S/2, 0.5, 0.5, maxWidth, 1.5, gg.AlignCenter)
w.Header().Set("Content-Type", "image/png")
err = png.Encode(w, dc.Image())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}