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
+20.2k Golang : Determine if directory is empty with os.File.Readdir() function
+6.3k Golang : Detect face in uploaded photo like GPlus
+20.6k Golang : Secure(TLS) connection between server and client
+4.8k Golang : A program that contain another program and executes it during run-time
+11.6k Golang : Convert(cast) float to int
+7.4k Golang : Accessing dataframe-go element by row, column and name example
+5.6k PHP : Convert CSV to JSON with YQL example
+8.2k Golang : Qt splash screen with delay example
+18.4k Golang : Logging with logrus
+11.9k Golang : Convert decimal number(integer) to IPv4 address
+13.8k Golang : unknown escape sequence error
+14.6k Golang : Send email with attachment(RFC2822) using Gmail API example