Golang image.png.Encode function example
package image/png
Golang image.png.Encode function usage example
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
out, err := os.Create("./output.png")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// generate some QR code look a like image
imgRect := image.Rect(0, 0, 100, 100)
img := image.NewGray(imgRect)
draw.Draw(img, img.Bounds(), &image.Uniform{color.White}, image.ZP, draw.Src)
for y := 0; y < 100; y += 10 {
for x := 0; x < 100; x += 10 {
fill := &image.Uniform{color.Black}
if rand.Intn(10)%2 == 0 {
fill = &image.Uniform{color.White}
}
draw.Draw(img, image.Rect(x, y, x+10, y+10), fill, image.ZP, draw.Src)
}
}
// ok, write out the data into the new PNG file
err = png.Encode(out, img)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Generated image to output.png \n")
}
Reference :
Advertisement
Something interesting
Tutorials
+6.8k Golang : Find the longest line of text example
+14.6k Golang : Missing Bazaar command
+25.3k Golang : Convert uint value to string type
+8.3k Golang : Check if integer is power of four example
+10.3k Golang : Embed secret text string into binary(executable) file
+15.3k Golang : Delete certain files in a directory
+10.8k PHP : Convert(cast) bigInt to string
+46.5k Golang : Marshal and unmarshal json.RawMessage struct example
+8.2k Prevent Write failed: Broken pipe problem during ssh session with screen command
+22.2k Golang : How to run Golang application such as web server in the background or as daemon?
+5.8k Linux : Disable and enable IPv4 forwarding
+18.7k Golang : Implement getters and setters