apps/shrink/image_test.go 2.4 K raw
1
package main
2
3
import (
4
	"bytes"
5
	"encoding/binary"
6
	"image"
7
	"image/color"
8
	"image/jpeg"
9
	"testing"
10
)
11
12
func jpegBytes(t *testing.T, w, h int) []byte {
13
	t.Helper()
14
	img := image.NewRGBA(image.Rect(0, 0, w, h))
15
	for y := 0; y < h; y++ {
16
		for x := 0; x < w; x++ {
17
			img.Set(x, y, color.RGBA{R: 200, G: 10, B: 10, A: 255})
18
		}
19
	}
20
	var b bytes.Buffer
21
	if err := jpeg.Encode(&b, img, nil); err != nil {
22
		t.Fatal(err)
23
	}
24
	return b.Bytes()
25
}
26
27
func TestBuildDownloadFilename(t *testing.T) {
28
	cases := map[string]string{"photo.jpg": "photo_compressed.webp", "photo": "photo_compressed.webp", "": "compressed_compressed.webp", "a.b.c.png": "a.b.c_compressed.webp"}
29
	for in, want := range cases {
30
		if got := buildDownloadFilename(in, "webp"); got != want {
31
			t.Fatalf("%q got %q want %q", in, got, want)
32
		}
33
	}
34
}
35
36
func TestCompressImage(t *testing.T) {
37
	if _, err := compressImage([]byte("not an image"), 80, 0); err == nil {
38
		t.Fatal("expected invalid image error")
39
	}
40
	out, err := compressImage(jpegBytes(t, 4, 2), 80, 0)
41
	if err != nil {
42
		t.Fatal(err)
43
	}
44
	if len(out) == 0 {
45
		t.Fatal("empty output")
46
	}
47
	resized, err := compressImage(jpegBytes(t, 4, 2), 80, 2)
48
	if err != nil {
49
		t.Fatal(err)
50
	}
51
	img, _, err := image.Decode(bytes.NewReader(resized))
52
	if err != nil {
53
		t.Fatal(err)
54
	}
55
	if img.Bounds().Dx() != 2 || img.Bounds().Dy() != 1 {
56
		t.Fatalf("resized bounds %v", img.Bounds())
57
	}
58
}
59
60
func makeExif(order binary.ByteOrder, magic string, gps bool) []byte {
61
	b := make([]byte, 40)
62
	copy(b[:2], magic)
63
	order.PutUint16(b[2:4], 42)
64
	order.PutUint32(b[4:8], 8)
65
	order.PutUint16(b[8:10], 1)
66
	if gps {
67
		order.PutUint16(b[10:12], 0x8825)
68
		order.PutUint32(b[18:22], 30)
69
		order.PutUint16(b[30:32], 7)
70
	} else {
71
		order.PutUint16(b[10:12], 0x010f)
72
	}
73
	return b
74
}
75
76
func TestStripGPS(t *testing.T) {
77
	short := []byte{1, 2, 3}
78
	if !bytes.Equal(stripGPS(short), short) {
79
		t.Fatal("short exif changed")
80
	}
81
	bad := []byte("not-tiff-data")
82
	if !bytes.Equal(stripGPS(bad), bad) {
83
		t.Fatal("bad header changed")
84
	}
85
	le := stripGPS(makeExif(binary.LittleEndian, "II", true))
86
	if binary.LittleEndian.Uint16(le[30:32]) != 0 {
87
		t.Fatal("little endian gps not zeroed")
88
	}
89
	be := stripGPS(makeExif(binary.BigEndian, "MM", true))
90
	if binary.BigEndian.Uint16(be[30:32]) != 0 {
91
		t.Fatal("big endian gps not zeroed")
92
	}
93
	noGPS := makeExif(binary.LittleEndian, "II", false)
94
	if !bytes.Equal(stripGPS(noGPS), noGPS) {
95
		t.Fatal("no gps changed")
96
	}
97
}