一个 golang http 实现图片服务代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"bytes"
"encoding/base64"
"flag"
"html/template"
"image"
"image/color"
"image/draw"
"image/jpeg"
"log"
"net/http"
"strconv"
)
var root = flag.String("root", ".", "file system path")
func main() {
http.HandleFunc("/blue/", blueHandler)
http.HandleFunc("/red/", redHandler)
http.Handle("/", http.FileServer(http.Dir(*root)))
log.Println("Listening on 8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
func blueHandler(w http.ResponseWriter, r *http.Request) {
m := image.NewRGBA(image.Rect(0, 0, 240, 240))
blue := color.RGBA{0, 0, 255, 255}
draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)
var img image.Image = m
writeImage(w, &img)
}
func redHandler(w http.ResponseWriter, r *http.Request) {
m := image.NewRGBA(image.Rect(0, 0, 240, 240))
blue := color.RGBA{255, 0, 0, 255}
draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)
var img image.Image = m
writeImageWithTemplate(w, &img)
}
var ImageTemplate string = `<!DOCTYPE html>
<html lang="en"><head></head>
<body><img src="data:image/jpg;base64,{{.Image}}"></body>`
// Writeimagewithtemplate encodes an image 'img' in jpeg format and writes it into ResponseWriter using a template.
func writeImageWithTemplate(w http.ResponseWriter, img *image.Image) {
buffer := new(bytes.Buffer)
if err := jpeg.Encode(buffer, *img, nil); err != nil {
log.Fatalln("unable to encode image.")
}
str := base64.StdEncoding.EncodeToString(buffer.Bytes())
if tmpl, err := template.New("image").Parse(ImageTemplate); err != nil {
log.Println("unable to parse image template.")
} else {
data := map[string]interface{}{"Image": str}
if err = tmpl.Execute(w, data); err != nil {
log.Println("unable to execute template.")
}
}
}
// writeImage encodes an image 'img' in jpeg format and writes it into ResponseWriter.
func writeImage(w http.ResponseWriter, img *image.Image) {
buffer := new(bytes.Buffer)
if err := jpeg.Encode(buffer, *img, nil); err != nil {
log.Println("unable to encode image.")
}
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
if _, err := w.Write(buffer.Bytes()); err != nil {
log.Println("unable to write image.")
}
}
来源 https://gist.github.com/santiaago/d6d681d14c5f3b3f5d69
本文网址: https://golangnote.com/topic/110.html 转摘请注明来源