summaryrefslogtreecommitdiffstats
path: root/htmlimg_test.go
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2026-07-11 13:09:00 -0230
committerSam Anthony <sam@samanthony.xyz>2026-07-11 13:09:00 -0230
commit6c1f9200881b859bcc6d7d5b0d9d37a5cc65eb60 (patch)
tree7095e5f52f3a62b08135810e59f9a233b861fc4e /htmlimg_test.go
downloadhtmlimg-6c1f9200881b859bcc6d7d5b0d9d37a5cc65eb60.zip
encode
Diffstat (limited to 'htmlimg_test.go')
-rw-r--r--htmlimg_test.go73
1 files changed, 73 insertions, 0 deletions
diff --git a/htmlimg_test.go b/htmlimg_test.go
new file mode 100644
index 0000000..a3fa857
--- /dev/null
+++ b/htmlimg_test.go
@@ -0,0 +1,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
+}