forked from yeqown/go-qrcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.go
95 lines (76 loc) · 2.06 KB
/
writer.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package compressed
import (
"image"
"image/color"
"image/png"
"io"
"os"
"github.com/yeqown/go-qrcode/v2"
)
type Option struct {
Padding int
BlockSize int
}
// compressedWriter implements issue#69, generating compressed images
// in some special situations, such as, network transferring.
// https://github.com/yeqown/go-qrcode/issues/69
type compressedWriter struct {
fd io.WriteCloser
option *Option
}
var (
backgroundColor = color.Gray{Y: 0xff}
foregroundColor = color.Gray{Y: 0x00}
)
func New(filename string, opt *Option) (qrcode.Writer, error) {
fd, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
return compressedWriter{fd: fd, option: opt}, nil
}
func NewWithWriter(writeCloser io.WriteCloser, opt *Option) qrcode.Writer {
return compressedWriter{fd: writeCloser, option: opt}
}
func (w compressedWriter) Write(mat qrcode.Matrix) error {
padding := w.option.Padding
blockWidth := w.option.BlockSize
width := mat.Width()*blockWidth + 2*padding
height := width
img := image.NewPaletted(
image.Rect(0, 0, width, height),
[]color.Color{backgroundColor, foregroundColor},
)
bgColor := uint8(img.Palette.Index(backgroundColor))
fgColor := uint8(img.Palette.Index(foregroundColor))
rectangle := func(x1, y1 int, x2, y2 int, img *image.Paletted, color uint8) {
for x := x1; x < x2; x++ {
for y := y1; y < y2; y++ {
pos := img.PixOffset(x, y)
img.Pix[pos] = color
}
}
}
// background
rectangle(0, 0, width, height, img, bgColor)
mat.Iterate(qrcode.IterDirection_COLUMN, func(x int, y int, v qrcode.QRValue) {
sx := x*blockWidth + padding
sy := y*blockWidth + padding
es := (x+1)*blockWidth + padding
ey := (y+1)*blockWidth + padding
if v.IsSet() {
rectangle(sx, sy, es, ey, img, fgColor)
}
//switch v.IsSet() {
//case false:
// gray = backgroundColor
//default:
// gray = foregroundColor
//}
})
encoder := png.Encoder{CompressionLevel: png.BestCompression}
return encoder.Encode(w.fd, img)
}
func (w compressedWriter) Close() error {
return w.fd.Close()
}