1// Copyright 2011 The Go Authors.  All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5/*
6Package qr encodes QR codes.
7*/
8package qr
9
10import (
11	"errors"
12	"image"
13	"image/color"
14
15	"rsc.io/qr/coding"
16)
17
18// A Level denotes a QR error correction level.
19// From least to most tolerant of errors, they are L, M, Q, H.
20type Level int
21
22const (
23	L Level = iota // 20% redundant
24	M              // 38% redundant
25	Q              // 55% redundant
26	H              // 65% redundant
27)
28
29// Encode returns an encoding of text at the given error correction level.
30func Encode(text string, level Level) (*Code, error) {
31	// Pick data encoding, smallest first.
32	// We could split the string and use different encodings
33	// but that seems like overkill for now.
34	var enc coding.Encoding
35	switch {
36	case coding.Num(text).Check() == nil:
37		enc = coding.Num(text)
38	case coding.Alpha(text).Check() == nil:
39		enc = coding.Alpha(text)
40	default:
41		enc = coding.String(text)
42	}
43
44	// Pick size.
45	l := coding.Level(level)
46	var v coding.Version
47	for v = coding.MinVersion; ; v++ {
48		if v > coding.MaxVersion {
49			return nil, errors.New("text too long to encode as QR")
50		}
51		if enc.Bits(v) <= v.DataBytes(l)*8 {
52			break
53		}
54	}
55
56	// Build and execute plan.
57	p, err := coding.NewPlan(v, l, 0)
58	if err != nil {
59		return nil, err
60	}
61	cc, err := p.Encode(enc)
62	if err != nil {
63		return nil, err
64	}
65
66	// TODO: Pick appropriate mask.
67
68	return &Code{cc.Bitmap, cc.Size, cc.Stride, 8}, nil
69}
70
71// A Code is a square pixel grid.
72// It implements image.Image and direct PNG encoding.
73type Code struct {
74	Bitmap []byte // 1 is black, 0 is white
75	Size   int    // number of pixels on a side
76	Stride int    // number of bytes per row
77	Scale  int    // number of image pixels per QR pixel
78}
79
80// Black returns true if the pixel at (x,y) is black.
81func (c *Code) Black(x, y int) bool {
82	return 0 <= x && x < c.Size && 0 <= y && y < c.Size &&
83		c.Bitmap[y*c.Stride+x/8]&(1<<uint(7-x&7)) != 0
84}
85
86// Image returns an Image displaying the code.
87func (c *Code) Image() image.Image {
88	return &codeImage{c}
89
90}
91
92// codeImage implements image.Image
93type codeImage struct {
94	*Code
95}
96
97var (
98	whiteColor color.Color = color.Gray{0xFF}
99	blackColor color.Color = color.Gray{0x00}
100)
101
102func (c *codeImage) Bounds() image.Rectangle {
103	d := (c.Size + 8) * c.Scale
104	return image.Rect(0, 0, d, d)
105}
106
107func (c *codeImage) At(x, y int) color.Color {
108	if c.Black(x, y) {
109		return blackColor
110	}
111	return whiteColor
112}
113
114func (c *codeImage) ColorModel() color.Model {
115	return color.GrayModel
116}
117