golang-generate-1pixel-image

Posted lavin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang-generate-1pixel-image相关的知识,希望对你有一定的参考价值。

package main

import (
    "bytes"
    "encoding/base64"
    "flag"
    "html/template"
    "image"
    "image/color"
    "image/draw"
    "image/jpeg"
    "log"
    "net/http"
    "strconv"
)

/*
@Time: 2018-12-20 16:50
@Desc:
*/

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, req *http.Request) {
    m := image.NewRGBA(image.Rect(0, 0, 6, 6))
    blue := color.RGBA{255, 255, 255, 1}
    draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)

    var img image.Image = m
    writeImage(w, &img)
}

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.")
    }
}

func writeImageWithTemplate(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.")
    }
    var ImageTemplate string = `<!DOCTYPE html>
    <html lang="en"><head></head>
    <body><img src="data:image/jpg;base64,{{.Image}}"></body>`
    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.")
        }
    }
}

golang生成1像素点图像;

参考:https://www.sanarias.com/blog/1214PlayingwithimagesinHTTPresponseingolang

以上是关于golang-generate-1pixel-image的主要内容,如果未能解决你的问题,请参考以下文章