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
+27.9k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+9.1k Golang : How to capture return values from goroutines?
+17.7k Golang : [json: cannot unmarshal object into Go value of type]
+13.4k Golang : Get constant name from value
+12k Golang : Convert a rune to unicode style string \u
+9.4k Golang : Web(Javascript) to server-side websocket example
+11k Golang : Create S3 bucket with official aws-sdk-go package
+8.4k Golang : Convert word to its plural form example
+14.8k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+22.1k Golang : Join arrays or slices example
+14.3k Golang : Get uploaded file name or access uploaded files
+21.6k Golang : GORM create record or insert new record into database example