diff --git a/captcha.go b/captcha.go index b01b5d8..4395765 100644 --- a/captcha.go +++ b/captcha.go @@ -3,6 +3,7 @@ package captcha import ( "bytes" + "encoding/base64" "image" "image/color" "image/draw" @@ -91,18 +92,57 @@ func (data *Data) WriteImage(w io.Writer) error { return png.Encode(w, data.img) } +// GetBase64Image encodes image data as base64 string. +// It returns base64 encoded PNG and possible encoding error. +func (data *Data) GetBase64Image() (string, error) { + var buff bytes.Buffer + + err := png.Encode(&buff, data.img) + if err != nil { + return "", err + } + + return base64.StdEncoding.EncodeToString(buff.Bytes()), nil +} + // 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) } +// GetBase64JPG encodes image data as base64 string. +// It returns base64 encoded JPG and possible encoding error. +func (data *Data) GetBase64JPG(o *jpeg.Options) (string, error) { + var buff bytes.Buffer + + err := jpeg.Encode(&buff, data.img, o) + if err != nil { + return "", err + } + + return base64.StdEncoding.EncodeToString(buff.Bytes()), nil +} + // WriteGIF encodes image data in GIF format and writes to an io.Writer. // It returns possible error from GIF encoding. func (data *Data) WriteGIF(w io.Writer, o *gif.Options) error { return gif.Encode(w, data.img, o) } +// GetBase64GIF encodes image data as base64 string. +// It returns base64 encoded GIF and possible encoding error. +func (data *Data) GetBase64GIF(o *gif.Options) (string, error) { + var buff bytes.Buffer + + err := gif.Encode(&buff, data.img, o) + if err != nil { + return "", err + } + + return base64.StdEncoding.EncodeToString(buff.Bytes()), nil +} + func init() { ttfFont, _ = freetype.ParseFont(ttf) } diff --git a/captcha_test.go b/captcha_test.go index 26b96f7..6989832 100644 --- a/captcha_test.go +++ b/captcha_test.go @@ -33,6 +33,24 @@ func TestSmallCaptcha(t *testing.T) { } } +func TestEncode(t *testing.T) { + data, err := New(150, 50) + if err != nil { + t.Fatal(err) + } + + buf := new(bytes.Buffer) + err = data.WriteImage(buf) + if err != nil { + t.Fatal(err) + } + + _, err = data.GetBase64Image() + if err != nil { + t.Fatal(err) + } +} + func TestEncodeJPG(t *testing.T) { data, err := New(150, 50) if err != nil { @@ -43,6 +61,11 @@ func TestEncodeJPG(t *testing.T) { if err != nil { t.Fatal(err) } + + _, err = data.GetBase64JPG(&jpeg.Options{Quality: 70}) + if err != nil { + t.Fatal(err) + } } func TestEncodeGIF(t *testing.T) { @@ -55,6 +78,11 @@ func TestEncodeGIF(t *testing.T) { if err != nil { t.Fatal(err) } + + _, err = data.GetBase64GIF(new(gif.Options)) + if err != nil { + t.Fatal(err) + } } func TestNewCaptchaOptions(t *testing.T) {