GolangNote

Golang笔记

一个golang http 实现图片服务的例子

Permalink

一个 golang http 实现图片服务代码

Go: 图片服务
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 转摘请注明来源

Related articles

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Write a Comment to "一个golang http 实现图片服务的例子"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms