-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
46 lines (39 loc) · 893 Bytes
/
encoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package captchy
import (
"bufio"
"bytes"
"encoding/base64"
"image"
"image/jpeg"
"image/png"
"io"
)
var _ Encoder = new(CaptchaEncoder)
type Encoder interface {
ToPNG(io.Writer) error
ToBase64(io.Writer) error
ToJPEG(io.Writer, *jpeg.Options) error
}
// CaptchaEncoder encode image.Image into common pic format
type CaptchaEncoder struct {
img image.Image
}
func (ce *CaptchaEncoder) ToPNG(w io.Writer) error {
buf := bufio.NewWriter(w)
defer buf.Flush()
return png.Encode(buf, ce.img)
}
func (ce *CaptchaEncoder) ToBase64(w io.Writer) error {
var b bytes.Buffer
err := png.Encode(&b, ce.img)
if err != nil {
return err
}
_, err = w.Write([]byte(base64.StdEncoding.EncodeToString(b.Bytes())))
return err
}
func (ce *CaptchaEncoder) ToJPEG(w io.Writer, opt *jpeg.Options) error {
buf := bufio.NewWriter(w)
defer buf.Flush()
return jpeg.Encode(buf, ce.img, opt)
}