diff --git a/captcha.go b/captcha.go index f8990e0..479682f 100644 --- a/captcha.go +++ b/captcha.go @@ -15,6 +15,7 @@ import ( "math/rand" "strconv" "time" + "image/jpeg" ) const charPreset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" @@ -80,6 +81,12 @@ func (data *Data) WriteImage(w io.Writer) error { return png.Encode(w, data.img) } +// WriteJPG encodes image data in JPEG format and writes to an io.Writer. +// It returns possible error from JPEG encoding +func (data *Data) WriteJPG(w io.Writer, o *jpeg.Options) error { + return jpeg.Encode(w, data.img, o) +} + func init() { ttfFont, _ = freetype.ParseFont(ttf) } diff --git a/captcha_test.go b/captcha_test.go index 9bdd150..5e54cc5 100644 --- a/captcha_test.go +++ b/captcha_test.go @@ -8,6 +8,7 @@ import ( "os" "testing" "errors" + "image/jpeg" ) func TestNewCaptcha(t *testing.T) { @@ -26,6 +27,15 @@ func TestSmallCaptcha(t *testing.T) { } } +func TestEncodeJPG(t *testing.T) { + data, err := New(150, 50) + if err != nil { + t.Fatal(err) + } + buf := new(bytes.Buffer) + data.WriteJPG(buf, &jpeg.Options{70}) +} + func TestNewCaptchaOptions(t *testing.T) { New(100, 34, func(options *Options) { options.BackgroundColor = color.Opaque