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.9k Golang : Use NLP to get sentences for each paragraph example
+8.1k Golang : How To Use Panic and Recover
+26.9k Golang : Force your program to run with root permissions
+23.6k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+6.5k Golang : Handling image beyond OpenCV video capture boundary
+7.4k Golang : Check to see if *File is a file or directory
+15.6k Golang : Force download file example
+8.2k Golang : Add build version and other information in executables
+11k How to test Facebook App on localhost ?
+9.4k Golang : How to protect your source code from client, hosting company or hacker?
+16.6k Golang : Delete files by extension
+25.7k Golang : missing Mercurial command