| 1 |
package qr |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"image" |
| 6 |
"image/color" |
| 7 |
"github.com/vitrun/qart/coding" |
| 8 |
) |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
type Level int |
| 13 |
|
| 14 |
const ( |
| 15 |
L Level = iota |
| 16 |
M |
| 17 |
Q |
| 18 |
H |
| 19 |
) |
| 20 |
|
| 21 |
|
| 22 |
func Encode(text string, level Level) (*Code, error) { |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
var enc coding.Encoding |
| 27 |
switch { |
| 28 |
case coding.Num(text).Check() == nil: |
| 29 |
enc = coding.Num(text) |
| 30 |
case coding.Alpha(text).Check() == nil: |
| 31 |
enc = coding.Alpha(text) |
| 32 |
default: |
| 33 |
enc = coding.String(text) |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
l := coding.Level(level) |
| 38 |
var v coding.Version |
| 39 |
for v = coding.MinVersion; ; v++ { |
| 40 |
if v > coding.MaxVersion { |
| 41 |
return nil, errors.New("text too long to encode as QR") |
| 42 |
} |
| 43 |
if enc.Bits(v) <= v.DataBytes(l)*8 { |
| 44 |
break |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
p, err := coding.NewPlan(v, l, 0) |
| 50 |
if err != nil { |
| 51 |
return nil, err |
| 52 |
} |
| 53 |
cc, err := p.Encode(enc) |
| 54 |
if err != nil { |
| 55 |
return nil, err |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
return &Code{cc.Bitmap, cc.Size, cc.Stride, 8}, nil |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
type Code struct { |
| 66 |
Bitmap []byte |
| 67 |
Size int |
| 68 |
Stride int |
| 69 |
Scale int |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
func (c *Code) Black(x, y int) bool { |
| 74 |
return 0 <= x && x < c.Size && 0 <= y && y < c.Size && |
| 75 |
c.Bitmap[y*c.Stride+x/8]&(1<<uint(7-x&7)) != 0 |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
func (c *Code) Image() image.Image { |
| 80 |
return &codeImage{c} |
| 81 |
|
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
type codeImage struct { |
| 86 |
*Code |
| 87 |
} |
| 88 |
|
| 89 |
var ( |
| 90 |
whiteColor color.Color = color.Gray{0xFF} |
| 91 |
blackColor color.Color = color.Gray{0x00} |
| 92 |
) |
| 93 |
|
| 94 |
func (c *codeImage) Bounds() image.Rectangle { |
| 95 |
d := (c.Size + 8) * c.Scale |
| 96 |
return image.Rect(0, 0, d, d) |
| 97 |
} |
| 98 |
|
| 99 |
func (c *codeImage) At(x, y int) color.Color { |
| 100 |
if c.Black(x, y) { |
| 101 |
return blackColor |
| 102 |
} |
| 103 |
return whiteColor |
| 104 |
} |
| 105 |
|
| 106 |
func (c *codeImage) ColorModel() color.Model { |
| 107 |
return color.GrayModel |
| 108 |
} |
| 109 |
|