January 2018
Intermediate to advanced
340 pages
8h 6m
English
This program will create a JPEG image with every pixel set to a random color. It is a simple program so we have just a jpeg image available to work with. The Go standard library comes with jpeg, gif, and png packages. The interface to all different image types is the same, so swapping from a jpeg to a gif or png package is very easy:
package mainimport ( "image" "image/jpeg" "log" "math/rand" "os")
func main() { // 100x200 pixels myImage := image.NewRGBA(image.Rect(0, 0, 100, 200)) for p := 0; p < 100*200; p++ { pixelOffset := 4 * p myImage.Pix[0+pixelOffset] = uint8(rand.Intn(256)) // Red myImage.Pix[1+pixelOffset] = uint8(rand.Intn(256)) // Green myImage.Pix[2+pixelOffset] = uint8(rand.Intn(256)) // ...
Read now
Unlock full access