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
+7k Web : How to see your website from different countries?
+14.1k Javascript : Prompt confirmation before exit
+5.6k Fix fatal error: evacuation not done in time problem
+17.6k Golang : Parse date string and convert to dd-mm-yyyy format
+7.2k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+12.2k Golang : Get remaining text such as id or filename after last segment in URL path
+13.9k Golang : convert(cast) string to float value
+36.6k Golang : Validate IP address
+7.5k Golang : How to stop user from directly running an executable file?
+7.4k Android Studio : How to detect camera, activate and capture example
+6.5k Golang : Combine slices of complex numbers and operation example
+32.1k Golang : Validate email address with regular expression