diff --git a/qrencode/bits.go b/qrencode/bits.go index dc03cee..74f8531 100644 --- a/qrencode/bits.go +++ b/qrencode/bits.go @@ -5,6 +5,7 @@ import ( "image" "image/color" "io" + "strings" ) // The test benchmark shows that encoding with boolBitVector/boolBitGrid is @@ -123,6 +124,52 @@ func (g *BitGrid) TerminalOutput(w io.Writer) { w.Write([]byte(newline)) } +// TerminalOutputCompress Encode the Grid in UNICODE blocks sequences and set the background according +// to the values in the BitGrid surrounded by a white frame +func (g *BitGrid) TerminalOutputCompress(w io.Writer) { + const ( + WHITE_ALL = string("\u2588") + WHITE_BLACK = string("\u2580") + BLACK_WHITE = string("\u2584") + BLACK_ALL = string(" ") + ) + + height := g.Height() + width := g.Width() + + borderTop := strings.Repeat(BLACK_WHITE, width+2) + "\n" + borderBottom := strings.Repeat(BLACK_WHITE, width+2) + "\n" + + var odd bool + w.Write([]byte(borderTop)) + for y := 0; y < height; y += 2 { + w.Write([]byte(WHITE_ALL)) + for x := 0; x < width; x++ { + b1 := g.Get(x, y) + //deal odd rows + b2 := false + if y+1 < height { + odd = true + b2 = g.Get(x, y+1) + } + + if b1 && b2 { + w.Write([]byte(BLACK_ALL)) + } else if b1 && !b2 { + w.Write([]byte(BLACK_WHITE)) + } else if !b1 && b2 { + w.Write([]byte(WHITE_BLACK)) + } else { + w.Write([]byte(WHITE_ALL)) + } + } + w.Write([]byte(WHITE_ALL + "\n")) + } + if !odd { + w.Write([]byte(borderBottom)) + } +} + // Return an image of the grid, with black blocks for true items and // white blocks for false items, with the given block size and a // default margin. diff --git a/qrencode/bits_test.go b/qrencode/bits_test.go new file mode 100644 index 0000000..541492b --- /dev/null +++ b/qrencode/bits_test.go @@ -0,0 +1,27 @@ +package qrencode + +import ( + "fmt" + "math/rand" + "os" + "testing" +) + +func TestTerminalOutput(t *testing.T) { + //gen random string + var b = make([]byte, 100) + _, err := rand.Read(b) + if err != nil { + t.Fatalf("rand.Read err: %v", err) + } + s := fmt.Sprintf("%x", b) + + grid, err := Encode(s, ECLevelL) + if err != nil { + t.Fatalf("Encode err: %v", err) + } + + //compare two qrcode size in terminal + grid.TerminalOutput(os.Stdout) + grid.TerminalOutputCompress(os.Stdout) +}