Golang image.png.Encoder.Encode function and CompressionLevel type example
package image/png
Golang image.png.Encoder.Encode function and CompressionLevel type 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)
}
}
var Enc png.Encoder
// set the best compression
Enc.CompressionLevel = -3 //BestCompression
// ok, write out the data into the new PNG file
err = Enc.Encode(out, img)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Generated image to output.png \n")
}
References :
http://golang.org/pkg/image/png/#Encoder
Advertisement
Something interesting
Tutorials
+5.6k Swift : Get substring with rangeOfString() function example
+6.1k nginx : force all pages to be SSL
+36k Golang : Get file last modified date and time
+6.3k Golang : Extract sub-strings
+5.2k Golang : PGX CopyFrom to insert rows into Postgres database
+17.4k Golang : Multi threading or run two processes or more example
+7.2k Golang : Check if one string(rune) is permutation of another string(rune)
+12.3k Golang : How to check if a string starts or ends with certain characters or words?
+6.1k Java : Human readable password generator
+9k Golang : Get SPF and DMARC from email headers to fight spam
+11.6k Android Studio : Create custom icons for your application example
+8.9k Golang : Find network service name from given port and protocol