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
|
package htmlimg_test
import (
"bytes"
"encoding/base64"
"image"
"image/color"
"image/png"
"math/rand/v2"
"regexp"
"testing"
"github.com/stretchr/testify/require"
"git.samanthony.xyz/htmlimg"
)
var tagExpr = regexp.MustCompile(`^<img src="data:image/png;base64,([A-Za-z0-9+/=]+)">$`)
func TestOutputMatchRegexp(t *testing.T) {
t.Parallel()
img := newImg(16)
tag, err := htmlimg.Encode(img)
require.NoError(t, err)
require.Regexp(t, tagExpr, tag)
}
func TestDecodeImg(t *testing.T) {
t.Parallel()
img := newImg(16)
// Encode <img> tag
tag, err := htmlimg.Encode(img)
require.NoError(t, err)
t.Log(tag)
// Extract and decode base64 data from tag to get png data
groups := tagExpr.FindStringSubmatch(string(tag))
require.Len(t, groups, 2)
b64 := groups[1]
decPng, err := base64.StdEncoding.DecodeString(b64)
require.NoError(t, err)
// Decoded png should match original image's png
encPng := new(bytes.Buffer)
err = png.Encode(encPng, img)
require.NoError(t, err)
require.Equal(t, encPng.Bytes(), decPng)
}
func BenchmarkEncode(b *testing.B) {
img := newImg(1024)
for b.Loop() {
htmlimg.Encode(img)
}
}
func newImg(size int) image.Image {
w, h := size, size
img := image.NewNRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
img.Set(x, y, color.NRGBA{
R: uint8(rand.IntN(256)),
G: uint8(rand.IntN(256)),
B: uint8(rand.IntN(256)),
A: uint8(rand.IntN(256)),
})
}
}
return img
}
|