先看一個簡單代碼, 它執行后會產生下面的300*500的png圖片文件:
代碼:
1: package main
2:
3: import (
4: "fmt"
5: "image"
6: "image/color"
7: "image/png"
8: "log"
9: "os"
10: )
11:
12: func main() {
13: const (
14: dx = 300
15: dy = 500
16: )
17:
18: // 需要保存的文件
19: imgcounter := 123
20: imgfile, _ := os.Create(fmt.Sprintf("%03d.png", imgcounter))
21: defer imgfile.Close()
22:
23: // 新建一個 指定大小的 RGBA位圖
24: img := image.NewNRGBA(image.Rect(0, 0, dx, dy))
25:
26: for y := 0; y < dy; y++ {
27: for x := 0; x < dx; x++ {
28: // 設置某個點的顏色,依次是 RGBA
29: img.Set(x, y, color.RGBA{uint8(x % 256), uint8(y % 256), 0, 255})
30: }
31: }
32:
33: // 以PNG格式保存文件
34: err := png.Encode(imgfile, img)
35: if err != nil {
36: log.Fatal(err)
37: }
38:
39: }
我們再看一個代碼,以http文件流的方式展示圖片,效果如下:
1: package main
2:
3: import (
4: "image"
5: "image/color"
6: "image/png"
7: "net/http"
8: "time"
9: )
10:
11: func pic(w http.ResponseWriter, req *http.Request) {
12: const (
13: dx = 300
14: dy = 500
15: )
16:
17: // 新建一個 指定大小的 RGBA位圖
18: img := image.NewNRGBA(image.Rect(0, 0, dx, dy))
19:
20: for y := 0; y < dy; y++ {
21: for x := 0; x < dx; x++ {
22: // 設置某個點的顏色,依次是 RGBA
23: img.Set(x, y, color.RGBA{uint8(x % 256), uint8(y % 256), 0, 255})
24: }
25: }
26:
27: // 圖片流方式輸出
28: w.Header().Set("Content-Type", "image/png")
29: png.Encode(w, img)
30: }
31:
32: func main() {
33: http.HandleFunc("/", pic)
34: s := &http.Server{
35: Addr: ":82",
36: ReadTimeout: 30 * time.Second,
37: WriteTimeout: 30 * time.Second,
38: MaxHeaderBytes: 1 << 20}
39: s.ListenAndServe()
40:
41: }
通過兩種方式來展示圖片,我們可以看到,上面兩個代碼最大的區別就是輸出源不一樣, 一個是到文件,一個是到http流. 而我們的代碼也很清晰的展示了這兩種方式只需要修改對應的實現即可.其他代碼是沒有變化的.
這里代碼中的 image.NewNRGBA 返回的 image對象是一個內存中的圖片。