diff --git a/README.md b/README.md index 4b5cfa3..7b68f2a 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ func handle(w http.ResponseWriter, r *http.Request) { ``` [documentation](https://godoc.org/github.com/steambap/captcha) | -[example](example/main.go) +[example](example/basic/main.go) ## sample image ![image](example/captcha.png) diff --git a/captcha.go b/captcha.go index a73fcc7..475d0cd 100644 --- a/captcha.go +++ b/captcha.go @@ -36,6 +36,9 @@ type Options struct { // CurveNumber is the number of curves to draw on captcha image. // It defaults to 2. CurveNumber int + // FontDPI controls scale of font. + // The default is 92.0. + FontDPI float64 width int height int @@ -47,6 +50,7 @@ func newDefaultOption(width, height int) *Options { CharPreset: charPreset, TextLength: 4, CurveNumber: 2, + FontDPI: 92.0, width: width, height: height, } @@ -184,7 +188,7 @@ func drawSineCurve(img *image.NRGBA, opts *Options) { func drawText(text string, img *image.NRGBA, opts *Options) error { ctx := freetype.NewContext() - ctx.SetDPI(92.0) + ctx.SetDPI(opts.FontDPI) ctx.SetClip(img.Bounds()) ctx.SetDst(img) ctx.SetHinting(font.HintingFull) diff --git a/example/index.html b/example/basic/index.html similarity index 100% rename from example/index.html rename to example/basic/index.html diff --git a/example/main.go b/example/basic/main.go similarity index 100% rename from example/main.go rename to example/basic/main.go diff --git a/example/load-font/index.html b/example/load-font/index.html new file mode 100644 index 0000000..cd731d5 --- /dev/null +++ b/example/load-font/index.html @@ -0,0 +1,10 @@ + + + + + Load Font + + + captcha + + \ No newline at end of file diff --git a/example/load-font/main.go b/example/load-font/main.go new file mode 100644 index 0000000..40c1d8e --- /dev/null +++ b/example/load-font/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "github.com/steambap/captcha" + "golang.org/x/image/font/gofont/goregular" + "html/template" + "net/http" +) + +func main() { + err := captcha.LoadFont(goregular.TTF) + if err != nil { + panic(err) + } + + http.HandleFunc("/", indexHandle) + http.HandleFunc("/captcha", captchaHandle) + fmt.Println("Server start at port 8080") + err = http.ListenAndServe(":8080", nil) + if err != nil { + panic(err) + } +} + +func indexHandle(w http.ResponseWriter, _ *http.Request) { + doc, err := template.ParseFiles("index.html") + if err != nil { + fmt.Fprint(w, err.Error()) + return + } + doc.Execute(w, nil) +} + +func captchaHandle(w http.ResponseWriter, _ *http.Request) { + img, err := captcha.New(150, 50, func(options *captcha.Options) { + options.FontDPI = 72.0 + }) + if err != nil { + fmt.Fprint(w, nil) + fmt.Println(err.Error()) + return + } + img.WriteTo(w) +} \ No newline at end of file