Add `Noise` option

This commit is contained in:
Weilin Shi 2017-12-11 16:12:44 +08:00
parent 57d17d0ed4
commit 8bb5ffd35d
2 changed files with 12 additions and 5 deletions

View File

@ -3,9 +3,6 @@ package captcha
import ( import (
"bytes" "bytes"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"image" "image"
"image/color" "image/color"
"image/draw" "image/draw"
@ -17,6 +14,10 @@ import (
"math/rand" "math/rand"
"strconv" "strconv"
"time" "time"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
) )
const charPreset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" const charPreset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@ -45,6 +46,10 @@ type Options struct {
// FontScale controls the scale of font. // FontScale controls the scale of font.
// The default is 1.0. // The default is 1.0.
FontScale float64 FontScale float64
// Noise controls the number of noise drawn.
// A noise dot is drawn for every 28 pixel by default.
// The default is 1.0.
Noise float64
width int width int
height int height int
@ -58,6 +63,7 @@ func newDefaultOption(width, height int) *Options {
CurveNumber: 2, CurveNumber: 2,
FontDPI: 72.0, FontDPI: 72.0,
FontScale: 1.0, FontScale: 1.0,
Noise: 1.0,
width: width, width: width,
height: height, height: height,
} }
@ -167,7 +173,7 @@ func randomText(opts *Options) (text string) {
} }
func drawNoise(img *image.NRGBA, opts *Options) { func drawNoise(img *image.NRGBA, opts *Options) {
noiseCount := (opts.width * opts.height) / 28 noiseCount := (opts.width * opts.height) / int(28.0/opts.Noise)
for i := 0; i < noiseCount; i++ { for i := 0; i < noiseCount; i++ {
x := rng.Intn(opts.width) x := rng.Intn(opts.width)
y := rng.Intn(opts.height) y := rng.Intn(opts.height)

View File

@ -3,13 +3,14 @@ package captcha
import ( import (
"bytes" "bytes"
"errors" "errors"
"golang.org/x/image/font/gofont/goregular"
"image/color" "image/color"
"image/gif" "image/gif"
"image/jpeg" "image/jpeg"
"math/rand" "math/rand"
"os" "os"
"testing" "testing"
"golang.org/x/image/font/gofont/goregular"
) )
func TestNewCaptcha(t *testing.T) { func TestNewCaptcha(t *testing.T) {