Skip to content

Instantly share code, notes, and snippets.

@santiaago
Last active March 18, 2023 07:57
Show Gist options
  • Save santiaago/d6d681d14c5f3b3f5d69 to your computer and use it in GitHub Desktop.
Save santiaago/d6d681d14c5f3b3f5d69 to your computer and use it in GitHub Desktop.
Playing with images
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.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment