-
Notifications
You must be signed in to change notification settings - Fork 2
/
gojpegoptim_test.go
74 lines (68 loc) · 1.54 KB
/
gojpegoptim_test.go
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
74
package gojpegoptim
import (
"bytes"
"image"
"image/color"
"image/jpeg"
"io/ioutil"
"os"
"testing"
)
func TestJpegOptimFromBuffer(t *testing.T) {
fi, err := ioutil.ReadFile("test.jpg")
if err != nil {
t.Fatal(err)
}
imgBytes, err := EncodeBytesOptimized(fi, &Options{100})
if err != nil {
t.Fatal(err)
}
_, err = jpeg.Decode(bytes.NewReader(imgBytes))
if err != nil {
t.Fatal(err)
}
gain := (len(fi) - len(imgBytes)) * 100 / len(fi)
t.Log("input size", len(fi), "output size", len(imgBytes), "gain", len(fi)-len(imgBytes), gain, "%")
if gain != 35 {
t.Fatal("Optimization failed")
}
}
func TestJpegOptimBadBuffer(t *testing.T) {
b := []byte{'g', 'o', 'l', 'a', 'n', 'g'}
_, err := EncodeBytesOptimized(b, &Options{100})
if err == nil {
t.Fatal("Should be detected as an error")
}
}
func TestEncodeImageWithJpegOptim(t *testing.T) {
m := image.NewRGBA(image.Rect(0, 0, 30, 30))
m.Set(5, 5, color.RGBA{255, 255, 255, 0})
w := new(bytes.Buffer)
err := Encode(w, m, &Options{100})
if err != nil {
t.Fatal(err)
}
b := w.Bytes()
if len(b) == 0 {
t.Fatal("error encoding, size is too small")
}
t.Log("output size", len(b), "image 30x30")
// open output file
fo, err := os.Create("outputcomp.jpg")
if err != nil {
t.Fatal(err)
}
defer fo.Close()
fo.Write(b)
}
func BenchmarkOptimize(b *testing.B) {
m := image.NewRGBA(image.Rect(0, 0, 30, 30))
m.Set(5, 5, color.RGBA{255, 255, 255, 0})
w := new(bytes.Buffer)
for i := 0; i < b.N; i++ {
err := Encode(w, m, &Options{100})
if err != nil {
b.Fatal(err)
}
}
}