Creating a PNG image in golang
The following very simple example creates a PNG image file in golang. It first creates a Image structure and then populates this with random data.
A file is then creating using os.Create, this is used as a io.Writer to which golang’s PNG encoder in image/png writes the encoded PNG data via the png.Encode function.
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 | package main import ( "image" "image/png" "image/color" "os" "math/rand" ) func main() { myimage := image.NewRGBA(image.Rectangle{image.Point{0,0},image.Point{100,100}}) // This loop just fills the image with random data for x := 0; x < 100; x++ { for y := 0; y < 100; y++ { c := color.RGBA{uint8( rand .Intn(255)),uint8( rand .Intn(255)),uint8( rand .Intn(255)),255} myimage.Set(x,y,c) } } myfile, _ := os.Create( "test.png" ) png.Encode(myfile, myimage) } |
you should `defer myfile.Close()`