diff options
Diffstat (limited to 'libgo/go/image/png/writer_test.go')
-rw-r--r-- | libgo/go/image/png/writer_test.go | 112 |
1 files changed, 110 insertions, 2 deletions
diff --git a/libgo/go/image/png/writer_test.go b/libgo/go/image/png/writer_test.go index 1107ea0e7fc..5d131ff823a 100644 --- a/libgo/go/image/png/writer_test.go +++ b/libgo/go/image/png/writer_test.go @@ -6,9 +6,12 @@ package png import ( "bytes" + "compress/zlib" + "encoding/binary" "fmt" "image" "image/color" + "io" "io/ioutil" "testing" ) @@ -61,12 +64,12 @@ func TestWriter(t *testing.T) { m1, err := readPNG(qfn) if err != nil { t.Error(fn, err) - return + continue } m2, err := encodeDecode(m1) if err != nil { t.Error(fn, err) - return + continue } // Compare the two. err = diff(m0, m2) @@ -77,6 +80,111 @@ func TestWriter(t *testing.T) { } } +func TestWriterPaletted(t *testing.T) { + const width, height = 32, 16 + + testCases := []struct { + plen int + bitdepth uint8 + datalen int + }{ + + { + plen: 256, + bitdepth: 8, + datalen: (1 + width) * height, + }, + + { + plen: 128, + bitdepth: 8, + datalen: (1 + width) * height, + }, + + { + plen: 16, + bitdepth: 4, + datalen: (1 + width/2) * height, + }, + + { + plen: 4, + bitdepth: 2, + datalen: (1 + width/4) * height, + }, + + { + plen: 2, + bitdepth: 1, + datalen: (1 + width/8) * height, + }, + } + + for _, tc := range testCases { + t.Run(fmt.Sprintf("plen-%d", tc.plen), func(t *testing.T) { + // Create a paletted image with the correct palette length + palette := make(color.Palette, tc.plen) + for i := range palette { + palette[i] = color.NRGBA{ + R: uint8(i), + G: uint8(i), + B: uint8(i), + A: 255, + } + } + m0 := image.NewPaletted(image.Rect(0, 0, width, height), palette) + + i := 0 + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + m0.SetColorIndex(x, y, uint8(i%tc.plen)) + i++ + } + } + + // Encode the image + var b bytes.Buffer + if err := Encode(&b, m0); err != nil { + t.Error(err) + return + } + const chunkFieldsLength = 12 // 4 bytes for length, name and crc + data := b.Bytes() + i = len(pngHeader) + + for i < len(data)-chunkFieldsLength { + length := binary.BigEndian.Uint32(data[i : i+4]) + name := string(data[i+4 : i+8]) + + switch name { + case "IHDR": + bitdepth := data[i+8+8] + if bitdepth != tc.bitdepth { + t.Errorf("got bitdepth %d, want %d", bitdepth, tc.bitdepth) + } + case "IDAT": + // Uncompress the image data + r, err := zlib.NewReader(bytes.NewReader(data[i+8 : i+8+int(length)])) + if err != nil { + t.Error(err) + return + } + n, err := io.Copy(ioutil.Discard, r) + if err != nil { + t.Errorf("got error while reading image data: %v", err) + } + if n != int64(tc.datalen) { + t.Errorf("got uncompressed data length %d, want %d", n, tc.datalen) + } + } + + i += chunkFieldsLength + int(length) + } + }) + + } +} + func TestWriterLevels(t *testing.T) { m := image.NewNRGBA(image.Rect(0, 0, 100, 100)) |