While I was writing test I ran into this strange behaviour that, when given a random image to png.Encode
, then decoding the given byte array again with png.Decode
it is all zeros (Despite the fact that is a image.NRGBA
image - that should be fixed for comparison)
I created a playground for my code here: https://play.golang.org/p/S6XJLVMOLyQ
But for completeness by example code is here:
package main
import (
"fmt"
"image"
"reflect"
"image/color"
"bytes"
"image/png"
"math/rand"
)
func main() {
width := 5
height := 5
upLeft := image.Point{0, 0}
lowRight := image.Point{width, height}
inImage := image.NewRGBA(image.Rectangle{upLeft, lowRight})
for x := 0; x < width; x++ {
for y := 0; y < height; y++ {
// Colors are defined by Red, Green, Blue, Alpha uint8 values.
randomColor := color.RGBA{
uint8(rand.Intn(255)),
uint8(rand.Intn(255)),
uint8(rand.Intn(255)),
0x00}
inImage.Set(x, y, randomColor)
}
}
out := new(bytes.Buffer)
err := png.Encode(out, inImage)
if err != nil {
panic("Something went wrong")
}
reader := bytes.NewReader(out.Bytes())
outImage, err := png.Decode(reader)
areEqual := reflect.DeepEqual(inImage, outImage)
// Might have to convert it to image.RGBA here - but still all bytes are zero now
fmt.Printf("Are Equal: %s\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", areEqual, inImage, outImage)
}
Which returns:
Are Equal: %!s(bool=false)
exp: &image.RGBA{Pix:[]uint8{0x56, 0x84, 0x7a, 0x0, 0xef, 0x60, 0x9b, 0x0, 0x10, 0x8a, 0x4d, 0x0, 0xfc, 0x76, 0x5e, 0x0, 0x65, 0x5a, 0xa5, 0x0, 0xfe, 0x97, 0x99, 0x0, 0xa7, 0x83, 0x32, 0x0, 0x92, 0xae, 0xb, 0x0, 0xd6, 0x7b, 0xde, 0x0, 0xab, 0x1, 0x17, 0x0, 0x73, 0x9b, 0x3d, 0x0, 0x42, 0x8f, 0x85, 0x0, 0x48, 0xd3, 0x2d, 0x0, 0x3d, 0x54, 0x81, 0x0, 0xce, 0x6b, 0xf8, 0x0, 0x96, 0x77, 0x97, 0x0, 0xed, 0x25, 0x34, 0x0, 0x9c, 0x67, 0xdc, 0x0, 0xcd, 0xfa, 0x53, 0x0, 0xb0, 0x85, 0x8d, 0x0, 0x2a, 0x3b, 0x58, 0x0, 0xd0, 0xb4, 0x96, 0x0, 0x9a, 0x30, 0x2b, 0x0, 0x12, 0x67, 0xaa, 0x0, 0x89, 0x53, 0xde, 0x0}, Stride:20, Rect:image.Rectangle{Min:image.Point{X:0, Y:0}, Max:image.Point{X:5, Y:5}}}
got: &image.NRGBA{Pix:[]uint8{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, Stride:20, Rect:image.Rectangle{Min:image.Point{X:0, Y:0}, Max:image.Point{X:5, Y:5}}}[39m