1 // PNG encode/decode round trip, pixel exact.
2 //
3 // image/png had no fixture: its encoder keeps a per-filter row cache
4 // (`cr [nFilter][]uint8`), an 8-byte chunk header, a 4-byte CRC footer and a
5 // 1024-byte PLTE staging buffer, all of which became slices. A filter that
6 // writes through a window of its row would show up as unfiltered bytes under a
7 // filter name that says otherwise, which only a decoded pixel comparison
8 // catches. Alpha is opaque here on purpose: RGBA is premultiplied in memory and
9 // PNG is not, so a translucent round trip is lossy by one and that is the
10 // format's arithmetic, not the encoder's.
11 //
12 // usage: png_roundtrip exit 0 when every pixel matches
13 package main
14 15 import (
16 "bytes"
17 "image"
18 "image/color"
19 "image/png"
20 )
21 22 func main() {
23 // Termination: a batch program must still be stoppable, so the entry
24 // handles the channel the runtime closes on SIGINT/SIGTERM.
25 select {
26 case <-shutdown:
27 return
28 default:
29 }
30 31 // a small RGBA image with an alpha ramp, encoded and decoded back
32 w := int32(37)
33 h := int32(23)
34 img := image.NewRGBA(image.Rectangle{Min: image.Point{0, 0}, Max: image.Point{w, h}})
35 for y := int32(0); y < h; y++ {
36 for x := int32(0); x < w; x++ {
37 img.SetRGBA(x, y, color.RGBA{
38 R: uint8(x * 7),
39 G: uint8(y * 11),
40 B: uint8((x ^ y) * 3),
41 A: 255,
42 })
43 }
44 }
45 var out bytes.Buffer
46 if err := png.Encode(&out, img); err != nil {
47 println("encode failed:", err.Error())
48 return
49 }
50 println("encoded bytes", int32(out.Len()).String())
51 got, derr := png.Decode(&out)
52 if derr != nil {
53 println("decode failed:", derr.Error())
54 return
55 }
56 b := got.Bounds()
57 if b.Dx() != w || b.Dy() != h {
58 println("bounds mismatch", b.Dx().String(), b.Dy().String())
59 return
60 }
61 // compare every pixel
62 for y := int32(0); y < h; y++ {
63 for x := int32(0); x < w; x++ {
64 want := img.RGBAAt(x, y)
65 hr, hg, hb, ha := got.At(x, y).RGBA()
66 if uint32(want.R)*0x101 != hr || uint32(want.G)*0x101 != hg || uint32(want.B)*0x101 != hb || uint32(want.A)*0x101 != ha {
67 println("pixel mismatch at", x, y)
68 println(" want", int32(want.R).String(), int32(want.G).String(), int32(want.B).String(), int32(want.A).String())
69 println(" have", int32(hr>>8).String(), int32(hg>>8).String(), int32(hb>>8).String(), int32(ha>>8).String())
70 return
71 }
72 }
73 }
74 println("png round trip ok")
75 }
76