Golang image.jpeg.Encode function and Option type example
package image/jpeg
Golang image.jpeg.Encode function usage example
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"math/rand"
"os"
"time"
)
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
out, err := os.Create("./output.jpg")
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 opt jpeg.Options
opt.Quality = 80
// ok, write out the data into the new JPEG file
err = jpeg.Encode(out, img, &opt) // put quality to 80% <------ here
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Generated image to output.jpg \n")
}
References :
Advertisement
Something interesting
Tutorials
+6.2k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+17.3k Golang : How to tell if a file is compressed either gzip or zip ?
+9.1k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+9.4k Android Studio : Indicate progression with ProgressBar example
+7.5k Golang : Dealing with struct's private part
+19.2k Golang : Check if directory exist and create if does not exist
+14.6k Golang : Missing Bazaar command
+8.4k Your page has meta tags in the body instead of the head
+12.4k Golang : Extract part of string with regular expression
+9.2k Golang : Write multiple lines or divide string into multiple lines
+10.9k Golang : Get UDP client IP address and differentiate clients by port number
+6.9k Golang : How to setup a disk space used monitoring service with Telegram bot