Commit a7744096 authored by santiaago's avatar santiaago
Browse files

accept a number and return always the same symmetric grid avatar

parent b4f98965
Loading
Loading
Loading
Loading
+2 −1
Original line number Diff line number Diff line
@@ -22,7 +22,8 @@ func main() {
	r.HandleFunc("/red/?", colors.Red)

	r.HandleFunc("/grid/?", grid.H6X6)
	r.HandleFunc("/grid/[0-8]?", grid.Color)
	r.HandleFunc("/grid/[0-8]/?", grid.Color)
	r.HandleFunc("/grid/square/[0-9]+/?", grid.Square)

	r.HandleFunc("/grid/random/?", grid.Random)
	r.HandleFunc("/grid/random/[0-8]/?", grid.RandomColor)
+33 −0
Original line number Diff line number Diff line
package grid

import (
	"crypto/md5"
	"fmt"
	"github.com/taironas/tinygraphs/colors"
	"github.com/taironas/tinygraphs/draw"
	"github.com/taironas/tinygraphs/misc"
	"github.com/taironas/tinygraphs/write"
	"image"
	"io"
	"log"
	"net/http"
)

// gridColorHandler is the handler for /grid/square/[0-9]+/?
// build a 6x6 grid with alternate colors based on the number passed in the url
func Square(w http.ResponseWriter, r *http.Request) {
	intID, err := misc.PermalinkID(r, 3)
	if err != nil {
		log.Printf("error when extracting permalink id: %v", err)
	} else {
		m := image.NewRGBA(image.Rect(0, 0, 240, 240))
		colorMap := colors.MapOfColorPatterns()
		h := md5.New()
		io.WriteString(h, string(intID))
		log.Printf("md5: %x", h.Sum(nil))
		key := fmt.Sprintf("%x", h.Sum(nil)[:])
		draw.Square(m, key, colorMap[0][0], colorMap[0][1])
		var img image.Image = m
		write.Image(w, &img)
	}
}
+44 −0
Original line number Diff line number Diff line
package draw

import (
	"encoding/hex"
	"image"
	"image/color"
	"log"
	"math"
	"math/rand"
	"strconv"
)

//drawGrid6X6 builds an image with 6X6 quadrants of alternate colors.
@@ -126,3 +129,44 @@ func RandomSymetricInXGrid6X6(m *image.RGBA, color1, color2 color.RGBA) {
		}
	}
}

func Square(m *image.RGBA, key string, color1, color2 color.RGBA) {
	size := m.Bounds().Size()
	squares := 6
	quad := size.X / squares
	middle := math.Ceil(float64(squares) / float64(2))
	colorMap := make(map[int]color.RGBA)
	var currentYQuadrand = 0
	for y := 0; y < size.Y; y++ {
		yQuadrant := y / quad
		if yQuadrant != currentYQuadrand {
			// when y quadrant changes, clear map
			colorMap = make(map[int]color.RGBA)
			currentYQuadrand = yQuadrant
		}
		for x := 0; x < size.X; x++ {
			xQuadrant := x / quad
			if _, ok := colorMap[xQuadrant]; !ok {
				if float64(xQuadrant) < middle {
					colorMap[xQuadrant] = colorFromKey(key, color1, color2, xQuadrant+3*yQuadrant)
				} else {
					colorMap[xQuadrant] = colorMap[squares-xQuadrant-1]
				}
			}
			m.Set(x, y, colorMap[xQuadrant])
		}
	}
}

func colorFromKey(key string, color1, color2 color.RGBA, index int) color.RGBA {
	s := hex.EncodeToString([]byte{key[index]})
	if r, err := strconv.ParseInt(s, 16, 0); err == nil {
		if r%2 == 0 {
			return color1
		}
		return color2
	} else {
		log.Println("Error calling ParseInt(%v, 16, 0)", s, err)
	}
	return color1
}