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(`^
$`)
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
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
}