Golang image.gif.Encode function example
package image/gif
Golang image.gif.Encode function usage example
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/gif"
"math/rand"
"os"
"time"
)
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
out, err := os.Create("./output.gif")
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)
}
}
var opt gif.Options
opt.NumColors = 256 // you can add more parameters if you want
// ok, write out the data into the new GIF file
err = gif.Encode(out, img, &opt) // put num of colors to 256 <------- here
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Generated image to output.gif \n")
}
Reference :
Advertisement
Something interesting
Tutorials
+11.1k Golang : Web routing/multiplex example
+5.6k Golang : Shortening import identifier
+28.8k Golang : Detect (OS) Operating System
+14.9k Golang : How to check for empty array string or string?
+5.7k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+15.6k Golang : rune literal not terminated error
+5k Golang : Calculate a pip value and distance to target profit example
+10.2k Golang : How to get quoted string into another string?
+12.1k Golang : Pagination with go-paginator configuration example
+9k Golang : Build and compile multiple source files
+7.5k Golang : Process json data with Jason package
+21.9k Golang : Use TLS version 1.2 and enforce server security configuration over client