Golang : 将图像保存为 PNG、JPEG 或 GIF 格式
本教程将演示如何将图像保存到文件中。 我们将学习如何生成一些随机图像并将内存中的内容保存为 PNG、JPG 和 GIF 文件。
基本上,代码几乎相同,除了用于演示如何使用 Encode 函数的轻微变体。
保存为JPG :
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%
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Generated image to output.jpg \n")
}
保存为PNG :
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)
}
}
// ok, write out the data into the new PNG file
err = png.Encode(out, img)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Generated image to output.png \n")
}
保存为GIF :
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/gif"
"math/rand"
"os"
"time"
)
func main() {
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
out, err := os.Create("./output.gif")
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 gif.Options
opt.NumColors = 256 // you can add more parameters if you want
// ok, write out the data into the new GIF file
err = gif.Encode(out, img, &opt) // put num of colors to 256
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Generated image to output.gif \n")
}
相关文章