Golang現在標準函式庫裡有 image,
可以讓使用者輸出jpg/png等格式的圖形.
來看一個簡單的建立png檔的程式.
// hello80
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"os"
)
func main() {
width, height := 128, 128
m := image.NewRGBA(image.Rect(0, 0, width, height))
drawGradient(*m)
outFilename := "gradient.png"
outfile, err := os.Create(outFilename)
if err != nil {
fmt.Println(err)
}
defer outfile.Close()
fmt.Printf("Saving image to: %s\n", outFilename)
png.Encode(outfile, m)
}
func drawGradient(m image.RGBA) {
size := m.Bounds().Size()
for x := 0; x < size.X; x++ {
for y := 0; y < size.Y; y++ {
mcolor := color.RGBA{
uint8(255 * x / size.X),
uint8(255 * y / size.Y),
55,
255}
m.Set(x, y, mcolor)
}
}
}
執行結果:
/hello80
Saving image to: gradient.png
圖形如: