// Copyright 2011 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/* Package qr encodes QR codes. */
package qr // import "rsc.io/qr" import ( ) // A Level denotes a QR error correction level. // From least to most tolerant of errors, they are L, M, Q, H. type Level int const ( L Level = iota // 20% redundant M // 38% redundant Q // 55% redundant H // 65% redundant ) // Encode returns an encoding of text at the given error correction level. func ( string, Level) (*Code, error) { // Pick data encoding, smallest first. // We could split the string and use different encodings // but that seems like overkill for now. var coding.Encoding switch { case coding.Num().Check() == nil: = coding.Num() case coding.Alpha().Check() == nil: = coding.Alpha() default: = coding.String() } // Pick size. := coding.Level() var coding.Version for = coding.MinVersion; ; ++ { if > coding.MaxVersion { return nil, errors.New("text too long to encode as QR") } if .Bits() <= .DataBytes()*8 { break } } // Build and execute plan. , := coding.NewPlan(, , 0) if != nil { return nil, } , := .Encode() if != nil { return nil, } // TODO: Pick appropriate mask. return &Code{.Bitmap, .Size, .Stride, 8}, nil } // A Code is a square pixel grid. // It implements image.Image and direct PNG encoding. type Code struct { Bitmap []byte // 1 is black, 0 is white Size int // number of pixels on a side Stride int // number of bytes per row Scale int // number of image pixels per QR pixel } // Black returns true if the pixel at (x,y) is black. func ( *Code) (, int) bool { return 0 <= && < .Size && 0 <= && < .Size && .Bitmap[*.Stride+/8]&(1<<uint(7-&7)) != 0 } // Image returns an Image displaying the code. func ( *Code) () image.Image { return &codeImage{} } // codeImage implements image.Image type codeImage struct { *Code } var ( whiteColor color.Color = color.Gray{0xFF} blackColor color.Color = color.Gray{0x00} ) func ( *codeImage) () image.Rectangle { := (.Size + 8) * .Scale return image.Rect(0, 0, , ) } func ( *codeImage) (, int) color.Color { if .Black(, ) { return blackColor } return whiteColor } func ( *codeImage) () color.Model { return color.GrayModel }