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
+6k Fontello : How to load and use fonts?
+8.9k Golang : GMail API create and send draft with simple upload attachment example
+11.1k Golang : Fix go.exe is not compatible with the version of Windows you're running
+5.4k Unix/Linux : How to archive and compress entire directory ?
+6.1k Golang : Scan forex opportunities by Bollinger bands
+10.3k Golang : Detect number of faces or vehicles in a photo
+6k Golang : Experimenting with the Rejang script
+4.7k Fix Google Analytics Redundant Hostnames problem
+7.1k Golang : Array mapping with Interface
+8.5k Linux/Unix : fatal: the Postfix mail system is already running
+14k Golang : Reverse IP address for reverse DNS lookup example
+5.3k Python : Convert(cast) string to bytes example