Skip to content

Commit

Permalink
Webservice: Support foreground/background color.
Browse files Browse the repository at this point in the history
  • Loading branch information
michiwend committed Jan 17, 2016
1 parent 60b51bb commit 9547559
Showing 1 changed file with 58 additions and 3 deletions.
61 changes: 58 additions & 3 deletions service/placeholder.go
Original file line number Diff line number Diff line change
@@ -1,37 +1,92 @@
package main

import (
"errors"
"image/color"
"image/png"
"net/http"
"strconv"
"strings"

log "github.com/Sirupsen/logrus"

"github.com/gorilla/mux"
"github.com/michiwend/goplaceholder"
)

func hexToRGB(h string) (uint8, uint8, uint8, error) {
rgb, err := strconv.ParseUint(string(h), 16, 32)
if err == nil {
return uint8(rgb >> 16), uint8((rgb >> 8) & 0xFF), uint8(rgb & 0xFF), nil
}
return 0, 0, 0, err
}

func normalizeHex(h string) string {
h = strings.TrimPrefix(h, "#")
if len(h) != 3 && len(h) != 6 {
return ""
}
if len(h) == 3 {
h = h[:1] + h[:1] + h[1:2] + h[1:2] + h[2:] + h[2:]
}
return h
}

func paramToColor(param, defaultValue string) (color.RGBA, error) {

if len(param) == 0 {
param = defaultValue
}

hexColor := normalizeHex(param)
if len(hexColor) == 0 {
return color.RGBA{}, errors.New("bad hex color format")
}

R, G, B, err := hexToRGB(hexColor)
if err != nil {
return color.RGBA{}, err
}

return color.RGBA{R, G, B, 255}, nil
}

func serveImage(w http.ResponseWriter, r *http.Request) {

params := mux.Vars(r)
r.ParseForm()
text := r.FormValue("text")

width, _ := strconv.ParseInt(params["width"], 10, 32)
height, _ := strconv.ParseInt(params["height"], 10, 32)
// FIXME err handling

text := r.FormValue("text")

if width > 4000 || height > 4000 {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte("image too large"))

foregroundValue := r.FormValue("fg")
backgroundValue := r.FormValue("bg")

fg, err := paramToColor(foregroundValue, "969696")
if err != nil {
http.Error(w, "Bad value for foreground color", http.StatusBadRequest)
log.WithField("color", foregroundValue).Error(err)
return
}
bg, err := paramToColor(backgroundValue, "CCCCCC")
if err != nil {
http.Error(w, "Bad value for background color", http.StatusBadRequest)
log.WithField("color", backgroundValue).Error(err)
return
}

img, err := goplaceholder.Placeholder(
text,
"/usr/share/fonts/TTF/DejaVuSans-Bold.ttf",
color.RGBA{150, 150, 150, 255},
color.RGBA{204, 204, 204, 255},
fg, bg,
int(width), int(height))

if err != nil {
Expand Down

0 comments on commit 9547559

Please sign in to comment.