~mendelmaleh/dummy

764aaa223b49056ffa4b7b36152fb91b87507db7 — Mendel E 11 days ago 4d97d48
Add minimal server
2 files changed, 91 insertions(+), 0 deletions(-)

A cmd/minimalserver/luxisr.ttf
A cmd/minimalserver/main.go
A cmd/minimalserver/luxisr.ttf => cmd/minimalserver/luxisr.ttf +0 -0

A cmd/minimalserver/main.go => cmd/minimalserver/main.go +91 -0
@@ 0,0 1,91 @@
package main

import (
	"image"
	"image/color"
	"image/draw"
	"image/png"
	"io/ioutil"
	"log"
	"net/http"
	"strings"

	"github.com/golang/freetype"
	"github.com/golang/freetype/truetype"
	"golang.org/x/image/font"
	"golang.org/x/image/math/fixed"
)

type Options struct {
	// image
	Width, Height int
	Colors        []color.RGBA

	// text
	Text      string
	Font      *truetype.Font
	Size, DPI float64
}

func main() {
	filebytes, err := ioutil.ReadFile("luxisr.ttf")
	if err != nil {
		log.Fatal(err)
	}

	ft, err := freetype.ParseFont(filebytes)
	if err != nil {
		log.Fatal(err)
	}

	opt := Options{
		// image
		Width:  2048,
		Height: 2048,
		Colors: []color.RGBA{
			color.RGBA{0x24, 0x29, 0x33, 0xff},
			color.RGBA{0xec, 0xef, 0xf4, 0xff},
		},

		// text
		Text: "t",
		Font: ft,
		Size: 110,
		DPI:  1152,
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// image
		im := image.NewRGBA(image.Rectangle{image.Point{}, image.Point{opt.Width, opt.Height}})
		draw.Draw(im, im.Bounds(), image.NewUniform(opt.Colors[0]), image.Point{}, draw.Src)

		// text
		if len(strings.TrimSpace(opt.Text)) > 0 {
			face := truetype.NewFace(opt.Font, &truetype.Options{
				Size:    opt.Size,
				DPI:     opt.DPI,
				Hinting: font.HintingNone,
			})

			drawer := &font.Drawer{
				Dst:  im,
				Src:  image.NewUniform(opt.Colors[1]),
				Face: face,
			}

			b, x := font.BoundString(face, opt.Text)
			y := b.Max.Y - b.Min.Y

			drawer.Dot = fixed.Point26_6{
				X: (fixed.I(opt.Width) - x) / 2,
				Y: (fixed.I(opt.Height) + y) / 2,
			}

			drawer.DrawString(opt.Text)
		}

		png.Encode(w, im)
	})

	log.Panic(http.ListenAndServe(":8080", nil))
}