pax_global_header00006660000000000000000000000064127232241750014517gustar00rootroot0000000000000052 comment=bf64b92db6b05651d6c25a3dabf2d543b360c0aa qart-0.1/000077500000000000000000000000001272322417500123265ustar00rootroot00000000000000qart-0.1/.gitignore000066400000000000000000000004261272322417500143200ustar00rootroot00000000000000# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test .idea *.iml qart qart-0.1/LICENSE000066400000000000000000000260731272322417500133430ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.qart-0.1/LICENSE.bsd000066400000000000000000000026161272322417500141070ustar00rootroot00000000000000Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. qart-0.1/README.md000066400000000000000000000005721272322417500136110ustar00rootroot00000000000000# Qart Instead of scribbling on redundant pieces and relying on error correction to preserve the meaning, qart engineers the encoded values to create the picture in a code with no inherent errors. ## Technical Details Check http://research.swtch.com/qart for detail. The original code is written by iRuss Cox and can be downloaded at code.google.com/p/rsc/source/browse/qr qart-0.1/coding/000077500000000000000000000000001272322417500135715ustar00rootroot00000000000000qart-0.1/coding/coding.go000066400000000000000000000456431272322417500153770ustar00rootroot00000000000000// 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.bsd file. // Package coding implements low-level QR coding details. package coding import ( "fmt" "strconv" "strings" "github.com/vitrun/qart/gf256" ) // Field is the field for QR error correction. var Field = gf256.NewField(0x11d, 2) // A Version represents a QR version. // The version specifies the size of the QR code: // a QR code with version v has 4v+17 pixels on a side. // Versions number from 1 to 40: the larger the version, // the more information the code can store. type Version int const MinVersion = 1 const MaxVersion = 40 func (v Version) String() string { return strconv.Itoa(int(v)) } func (v Version) sizeClass() int { if v <= 9 { return 0 } if v <= 26 { return 1 } return 2 } // DataBytes returns the number of data bytes that can be // stored in a QR code with the given version and level. func (v Version) DataBytes(l Level) int { vt := &vtab[v] lev := &vt.level[l] return vt.bytes - lev.nblock*lev.check } // Encoding implements a QR data encoding scheme. // The implementations--Numeric, Alphanumeric, and String--specify // the character set and the mapping from UTF-8 to code bits. // The more restrictive the mode, the fewer code bits are needed. type Encoding interface { Check() error Bits(v Version) int Encode(b *Bits, v Version) } type Bits struct { b []byte nbit int } func (b *Bits) Reset() { b.b = b.b[:0] b.nbit = 0 } func (b *Bits) Bits() int { return b.nbit } func (b *Bits) Bytes() []byte { if b.nbit%8 != 0 { panic("fractional byte") } return b.b } func (b *Bits) Append(p []byte) { if b.nbit%8 != 0 { panic("fractional byte") } b.b = append(b.b, p...) b.nbit += 8 * len(p) } func (b *Bits) Write(v uint, nbit int) { for nbit > 0 { n := nbit if n > 8 { n = 8 } if b.nbit%8 == 0 { b.b = append(b.b, 0) } else { m := -b.nbit & 7 if n > m { n = m } } b.nbit += n sh := uint(nbit - n) b.b[len(b.b)-1] |= uint8(v >> sh << uint(-b.nbit&7)) v -= v >> sh << sh nbit -= n } } // Num is the encoding for numeric data. // The only valid characters are the decimal digits 0 through 9. type Num string func (s Num) String() string { return fmt.Sprintf("Num(%#q)", string(s)) } func (s Num) Check() error { for _, c := range s { if c < '0' || '9' < c { return fmt.Errorf("non-numeric string %#q", string(s)) } } return nil } var numLen = [3]int{10, 12, 14} func (s Num) Bits(v Version) int { return 4 + numLen[v.sizeClass()] + (10*len(s)+2)/3 } func (s Num) Encode(b *Bits, v Version) { b.Write((uint)(1), 4) b.Write(uint(len(s)), numLen[v.sizeClass()]) var i int for i = 0; i+3 <= len(s); i += 3 { w := uint(s[i]-'0')*100 + uint(s[i+1]-'0')*10 + uint(s[i+2]-'0') b.Write(w, 10) } switch len(s) - i { case 1: w := uint(s[i] - '0') b.Write(w, 4) case 2: w := uint(s[i]-'0')*10 + uint(s[i+1]-'0') b.Write(w, 7) } } // Alpha is the encoding for alphanumeric data. // The valid characters are 0-9A-Z$%*+-./: and space. type Alpha string const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:" func (s Alpha) String() string { return fmt.Sprintf("Alpha(%#q)", string(s)) } func (s Alpha) Check() error { for _, c := range s { if strings.IndexRune(alphabet, c) < 0 { return fmt.Errorf("non-alphanumeric string %#q", string(s)) } } return nil } var alphaLen = [3]int{9, 11, 13} func (s Alpha) Bits(v Version) int { return 4 + alphaLen[v.sizeClass()] + (11*len(s)+1)/2 } func (s Alpha) Encode(b *Bits, v Version) { b.Write((uint)(2), 4) b.Write(uint(len(s)), alphaLen[v.sizeClass()]) var i int for i = 0; i+2 <= len(s); i += 2 { w := uint(strings.IndexRune(alphabet, rune(s[i])))*45 + uint(strings.IndexRune(alphabet, rune(s[i+1]))) b.Write(w, 11) } if i < len(s) { w := uint(strings.IndexRune(alphabet, rune(s[i]))) b.Write(w, 6) } } // String is the encoding for 8-bit data. All bytes are valid. type String string func (s String) String() string { return fmt.Sprintf("String(%#q)", string(s)) } func (s String) Check() error { return nil } var stringLen = [3]int{8, 16, 16} func (s String) Bits(v Version) int { return 4 + stringLen[v.sizeClass()] + 8*len(s) } func (s String) Encode(b *Bits, v Version) { b.Write((uint)(4), 4) b.Write(uint(len(s)), stringLen[v.sizeClass()]) for i := 0; i < len(s); i++ { b.Write(uint(s[i]), 8) } } // A Pixel describes a single pixel in a QR code. type Pixel uint32 const ( Black Pixel = 1 << iota Invert ) func (p Pixel) Offset() uint { return uint(p >> 6) } func OffsetPixel(o uint) Pixel { return Pixel(o << 6) } func (r PixelRole) Pixel() Pixel { return Pixel(r << 2) } func (p Pixel) Role() PixelRole { return PixelRole(p>>2) & 15 } func (p Pixel) String() string { s := p.Role().String() if p&Black != 0 { s += "+black" } if p&Invert != 0 { s += "+invert" } s += "+" + strconv.FormatUint(uint64(p.Offset()), 10) return s } // A PixelRole describes the role of a QR pixel. type PixelRole uint32 const ( _ PixelRole = iota Position // position squares (large) Alignment // alignment squares (small) Timing // timing strip between position squares Format // format metadata PVersion // version pattern Unused // unused pixel Data // data bit Check // error correction check bit Extra ) var roles = []string{ "", "position", "alignment", "timing", "format", "pversion", "unused", "data", "check", "extra", } func (r PixelRole) String() string { if Position <= r && r <= Check { return roles[r] } return strconv.Itoa(int(r)) } // A Level represents 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 M Q H ) func (l Level) String() string { if L <= l && l <= H { return "LMQH"[l : l+1] } return strconv.Itoa(int(l)) } // A Code is a square pixel grid. 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 } func (c *Code) Black(x, y int) bool { return 0 <= x && x < c.Size && 0 <= y && y < c.Size && c.Bitmap[y*c.Stride+x/8]&(1<= pad { break } b.Write((uint)(0x11), 8) } } } func (b *Bits) AddCheckBytes(v Version, l Level) { nd := v.DataBytes(l) if b.nbit < nd*8 { b.Pad(nd*8 - b.nbit) } if b.nbit != nd*8 { panic("qr: too much data") } dat := b.Bytes() vt := &vtab[v] lev := &vt.level[l] db := nd / lev.nblock extra := nd % lev.nblock chk := make([]byte, lev.check) rs := gf256.NewRSEncoder(Field, lev.check) for i := 0; i < lev.nblock; i++ { if i == lev.nblock-extra { db++ } rs.ECC(dat[:db], chk) b.Append(chk) dat = dat[db:] } if len(b.Bytes()) != vt.bytes { panic("qr: internal error") } } func (p *Plan) Encode(text ...Encoding) (*Code, error) { var b Bits for _, t := range text { if err := t.Check(); err != nil { return nil, err } t.Encode(&b, p.Version) } if b.Bits() > p.DataBytes*8 { return nil, fmt.Errorf("cannot encode %d bits into %d-bit code", b.Bits(), p.DataBytes*8) } b.AddCheckBytes(p.Version, p.Level) bytes := b.Bytes() // Now we have the checksum bytes and the data bytes. // Construct the actual code. c := &Code{Size: len(p.Pixel), Stride: (len(p.Pixel) + 7) &^ 7} c.Bitmap = make([]byte, c.Stride*c.Size) crow := c.Bitmap for _, row := range p.Pixel { for x, pix := range row { switch pix.Role() { case Data, Check: o := pix.Offset() if bytes[o/8]&(1< 40 { return nil, fmt.Errorf("invalid QR version %d", int(v)) } siz := 17 + int(v)*4 m := grid(siz) p.Pixel = m // Timing markers (overwritten by boxes). const ti = 6 // timing is in row/column 6 (counting from 0) for i := range m { p := Timing.Pixel() if i&1 == 0 { p |= Black } m[i][ti] = p m[ti][i] = p } // Position boxes. posBox(m, 0, 0) posBox(m, siz-7, 0) posBox(m, 0, siz-7) // Alignment boxes. info := &vtab[v] for x := 4; x+5 < siz; { for y := 4; y+5 < siz; { // don't overwrite timing markers if (x < 7 && y < 7) || (x < 7 && y+5 >= siz-7) || (x+5 >= siz-7 && y < 7) { } else { alignBox(m, x, y) } if y == 4 { y = info.apos } else { y += info.astride } } if x == 4 { x = info.apos } else { x += info.astride } } // Version pattern. pat := vtab[v].pattern if pat != 0 { v := pat for x := 0; x < 6; x++ { for y := 0; y < 3; y++ { p := PVersion.Pixel() if v&1 != 0 { p |= Black } m[siz-11+y][x] = p m[x][siz-11+y] = p v >>= 1 } } } // One lonely black pixel m[siz-8][8] = Unused.Pixel() | Black return p, nil } // fplan adds the format pixels func fplan(l Level, m Mask, p *Plan) error { // Format pixels. fb := uint32(l^1) << 13 // level: L=01, M=00, Q=11, H=10 fb |= uint32(m) << 10 // mask const formatPoly = 0x537 rem := fb for i := 14; i >= 10; i-- { if rem&(1<>i)&1 == 1 { pix |= Black } if (invert>>i)&1 == 1 { pix ^= Invert | Black } // top left switch { case i < 6: p.Pixel[i][8] = pix case i < 8: p.Pixel[i+1][8] = pix case i < 9: p.Pixel[8][7] = pix default: p.Pixel[8][14-i] = pix } // bottom right switch { case i < 8: p.Pixel[8][siz-1-int(i)] = pix default: p.Pixel[siz-1-int(14-i)][8] = pix } } return nil } // lplan edits a version-only Plan to add information // about the error correction levels. func lplan(v Version, l Level, p *Plan) error { p.Level = l nblock := vtab[v].level[l].nblock ne := vtab[v].level[l].check nde := (vtab[v].bytes - ne*nblock) / nblock extra := (vtab[v].bytes - ne*nblock) % nblock dataBits := (nde*nblock + extra) * 8 checkBits := ne * nblock * 8 p.DataBytes = vtab[v].bytes - ne*nblock p.CheckBytes = ne * nblock p.Blocks = nblock // Make data + checksum pixels. data := make([]Pixel, dataBits) for i := range data { data[i] = Data.Pixel() | OffsetPixel(uint(i)) } check := make([]Pixel, checkBits) for i := range check { check[i] = Check.Pixel() | OffsetPixel(uint(i+dataBits)) } // Split into blocks. dataList := make([][]Pixel, nblock) checkList := make([][]Pixel, nblock) for i := 0; i < nblock; i++ { // The last few blocks have an extra data byte (8 pixels). nd := nde if i >= nblock-extra { nd++ } dataList[i], data = data[0:nd*8], data[nd*8:] checkList[i], check = check[0:ne*8], check[ne*8:] } if len(data) != 0 || len(check) != 0 { panic("data/check math") } // Build up bit sequence, taking first byte of each block, // then second byte, and so on. Then checksums. bits := make([]Pixel, dataBits+checkBits) dst := bits for i := 0; i < nde+1; i++ { for _, b := range dataList { if i*8 < len(b) { copy(dst, b[i*8:(i+1)*8]) dst = dst[8:] } } } for i := 0; i < ne; i++ { for _, b := range checkList { if i*8 < len(b) { copy(dst, b[i*8:(i+1)*8]) dst = dst[8:] } } } if len(dst) != 0 { panic("dst math") } // Sweep up pair of columns, // then down, assigning to right then left pixel. // Repeat. // See Figure 2 of http://www.pclviewer.com/rs2/qrtopology.htm siz := len(p.Pixel) rem := make([]Pixel, 7) for i := range rem { rem[i] = Extra.Pixel() } src := append(bits, rem...) for x := siz; x > 0; { for y := siz - 1; y >= 0; y-- { if p.Pixel[y][x-1].Role() == 0 { p.Pixel[y][x-1], src = src[0], src[1:] } if p.Pixel[y][x-2].Role() == 0 { p.Pixel[y][x-2], src = src[0], src[1:] } } x -= 2 if x == 7 { // vertical timing strip x-- } for y := 0; y < siz; y++ { if p.Pixel[y][x-1].Role() == 0 { p.Pixel[y][x-1], src = src[0], src[1:] } if p.Pixel[y][x-2].Role() == 0 { p.Pixel[y][x-2], src = src[0], src[1:] } } x -= 2 } return nil } // mplan edits a version+level-only Plan to add the mask. func mplan(m Mask, p *Plan) error { p.Mask = m for y, row := range p.Pixel { for x, pix := range row { if r := pix.Role(); (r == Data || r == Check || r == Extra) && p.Mask.Invert(y, x) { row[x] ^= Black | Invert } } } return nil } // posBox draws a position (large) box at upper left x, y. func posBox(m [][]Pixel, x, y int) { pos := Position.Pixel() // box for dy := 0; dy < 7; dy++ { for dx := 0; dx < 7; dx++ { p := pos if dx == 0 || dx == 6 || dy == 0 || dy == 6 || 2 <= dx && dx <= 4 && 2 <= dy && dy <= 4 { p |= Black } m[y+dy][x+dx] = p } } // white border for dy := -1; dy < 8; dy++ { if 0 <= y+dy && y+dy < len(m) { if x > 0 { m[y+dy][x-1] = pos } if x+7 < len(m) { m[y+dy][x+7] = pos } } } for dx := -1; dx < 8; dx++ { if 0 <= x+dx && x+dx < len(m) { if y > 0 { m[y-1][x+dx] = pos } if y+7 < len(m) { m[y+7][x+dx] = pos } } } } // alignBox draw an alignment (small) box at upper left x, y. func alignBox(m [][]Pixel, x, y int) { // box align := Alignment.Pixel() for dy := 0; dy < 5; dy++ { for dx := 0; dx < 5; dx++ { p := align if dx == 0 || dx == 4 || dy == 0 || dy == 4 || dx == 2 && dy == 2 { p |= Black } m[y+dy][x+dx] = p } } } qart-0.1/gf256/000077500000000000000000000000001272322417500131575ustar00rootroot00000000000000qart-0.1/gf256/gf256.go000066400000000000000000000117751272322417500143520ustar00rootroot00000000000000// Copyright 2010 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.bsd file. // Package gf256 implements arithmetic over the Galois Field GF(256). package gf256 import "strconv" // A Field represents an instance of GF(256) defined by a specific polynomial. type Field struct { log [256]byte // log[0] is unused exp [510]byte } // NewField returns a new field corresponding to the polynomial poly // and generator α. The Reed-Solomon encoding in QR codes uses // polynomial 0x11d with generator 2. // // The choice of generator α only affects the Exp and Log operations. func NewField(poly, α int) *Field { if poly < 0x100 || poly >= 0x200 || reducible(poly) { panic("gf256: invalid polynomial: " + strconv.Itoa(poly)) } var f Field x := 1 for i := 0; i < 255; i++ { if x == 1 && i != 0 { panic("gf256: invalid generator " + strconv.Itoa(α) + " for polynomial " + strconv.Itoa(poly)) } f.exp[i] = byte(x) f.exp[i+255] = byte(x) f.log[x] = byte(i) x = mul(x, α, poly) } f.log[0] = 255 for i := 0; i < 255; i++ { if f.log[f.exp[i]] != byte(i) { panic("bad log") } if f.log[f.exp[i+255]] != byte(i) { panic("bad log") } } for i := 1; i < 256; i++ { if f.exp[f.log[i]] != byte(i) { panic("bad log") } } return &f } // nbit returns the number of significant in p. func nbit(p int) uint { n := uint(0) for ; p > 0; p >>= 1 { n++ } return n } // polyDiv divides the polynomial p by q and returns the remainder. func polyDiv(p, q int) int { np := nbit(p) nq := nbit(q) for ; np >= nq; np-- { if p&(1<<(np-1)) != 0 { p ^= q << (np - nq) } } return p } // mul returns the product x*y mod poly, a GF(256) multiplication. func mul(x, y, poly int) int { z := 0 for x > 0 { if x&1 != 0 { z ^= y } x >>= 1 y <<= 1 if y&0x100 != 0 { y ^= poly } } return z } // reducible reports whether p is reducible. func reducible(p int) bool { // Multiplying n-bit * n-bit produces (2n-1)-bit, // so if p is reducible, one of its factors must be // of np/2+1 bits or fewer. np := nbit(p) for q := 2; q < int(1<<(np/2+1)); q++ { if polyDiv(p, q) == 0 { return true } } return false } // Add returns the sum of x and y in the field. func (f *Field) Add(x, y byte) byte { return x ^ y } // Exp returns the the base-α exponential of e in the field. // If e < 0, Exp returns 0. func (f *Field) Exp(e int) byte { if e < 0 { return 0 } return f.exp[e%255] } // Log returns the base-α logarithm of x in the field. // If x == 0, Log returns -1. func (f *Field) Log(x byte) int { if x == 0 { return -1 } return int(f.log[x]) } // Inv returns the multiplicative inverse of x in the field. // If x == 0, Inv returns 0. func (f *Field) Inv(x byte) byte { if x == 0 { return 0 } return f.exp[255-f.log[x]] } // Mul returns the product of x and y in the field. func (f *Field) Mul(x, y byte) byte { if x == 0 || y == 0 { return 0 } return f.exp[int(f.log[x])+int(f.log[y])] } // An RSEncoder implements Reed-Solomon encoding // over a given field using a given number of error correction bytes. type RSEncoder struct { f *Field c int gen []byte lgen []byte p []byte } func (f *Field) gen(e int) (gen, lgen []byte) { // p = 1 p := make([]byte, e+1) p[e] = 1 for i := 0; i < e; i++ { // p *= (x + Exp(i)) // p[j] = p[j]*Exp(i) + p[j+1]. c := f.Exp(i) for j := 0; j < e; j++ { p[j] = f.Mul(p[j], c) ^ p[j+1] } p[e] = f.Mul(p[e], c) } // lp = log p. lp := make([]byte, e+1) for i, c := range p { if c == 0 { lp[i] = 255 } else { lp[i] = byte(f.Log(c)) } } return p, lp } // NewRSEncoder returns a new Reed-Solomon encoder // over the given field and number of error correction bytes. func NewRSEncoder(f *Field, c int) *RSEncoder { gen, lgen := f.gen(c) return &RSEncoder{f: f, c: c, gen: gen, lgen: lgen} } // ECC writes to check the error correcting code bytes // for data using the given Reed-Solomon parameters. func (rs *RSEncoder) ECC(data []byte, check []byte) { if len(check) < rs.c { panic("gf256: invalid check byte length") } if rs.c == 0 { return } // The check bytes are the remainder after dividing // data padded with c zeros by the generator polynomial. // p = data padded with c zeros. var p []byte n := len(data) + rs.c if len(rs.p) >= n { p = rs.p } else { p = make([]byte, n) } copy(p, data) for i := len(data); i < len(p); i++ { p[i] = 0 } // Divide p by gen, leaving the remainder in p[len(data):]. // p[0] is the most significant term in p, and // gen[0] is the most significant term in the generator, // which is always 1. // To avoid repeated work, we store various values as // lv, not v, where lv = log[v]. f := rs.f lgen := rs.lgen[1:] for i := 0; i < len(data); i++ { c := p[i] if c == 0 { continue } q := p[i+1:] exp := f.exp[f.log[c]:] for j, lg := range lgen { if lg != 255 { // lgen uses 255 for log 0 q[j] ^= exp[lg] } } } copy(check, p[len(data):]) rs.p = p } qart-0.1/img.go000066400000000000000000000332161272322417500134360ustar00rootroot00000000000000// Package qart generates a pretty qr img /** * Copyright ©2014-04-07 Alex */ package qart import ( "bytes" "fmt" "github.com/vitrun/qart/coding" "github.com/vitrun/qart/gf256" "github.com/vitrun/qart/qr" "image" "image/png" _ "image/jpeg" "math/rand" "sort" ) type pixinfo struct { X int Y int Pix coding.Pixel Targ byte DTarg int Contrast int HardZero bool Block *bitBlock Bit uint } type bitBlock struct { DataBytes int CheckBytes int B []byte M [][]byte Tmp []byte RS *gf256.RSEncoder bdata []byte cdata []byte } func (b *bitBlock) check() { b.RS.ECC(b.B[:b.DataBytes], b.Tmp) if !bytes.Equal(b.B[b.DataBytes:], b.Tmp) { fmt.Printf("ecc mismatch\n%x\n%x\n", b.B[b.DataBytes:], b.Tmp) panic("mismatch") } } func (b *bitBlock) reset(bi uint, bval byte) { if (b.B[bi/8]>>(7-bi&7))&1 == bval { // already has desired bit return } // rows that have already been set m := b.M[len(b.M):cap(b.M)] for _, row := range m { if row[bi/8]&(1<<(7-bi&7)) != 0 { // Found it. for j, v := range row { b.B[j] ^= v } return } } panic("reset of unset bit") } func (b *bitBlock) canSet(bi uint, bval byte) bool { found := false m := b.M for j, row := range m { if row[bi/8]&(1<<(7-bi&7)) == 0 { continue } if !found { found = true if j != 0 { m[0], m[j] = m[j], m[0] } continue } for k := range row { row[k] ^= m[0][k] } } if !found { return false } targ := m[0] // Subtract from saved-away rows too. for _, row := range m[len(m):cap(m)] { if row[bi/8]&(1<<(7-bi&7)) == 0 { continue } for k := range row { row[k] ^= targ[k] } } // Found a row with bit #bi == 1 and cut that bit from all the others. // Apply to data and remove from m. if (b.B[bi/8]>>(7-bi&7))&1 != bval { for j, v := range targ { b.B[j] ^= v } } b.check() n := len(m) - 1 m[0], m[n] = m[n], m[0] b.M = m[:n] for _, row := range b.M { if row[bi/8]&(1<<(7-bi&7)) != 0 { panic("did not reduce") } } return true } func (b *bitBlock) copyOut() { b.check() copy(b.bdata, b.B[:b.DataBytes]) copy(b.cdata, b.B[b.DataBytes:]) } type pixOrder struct { Off int Priority int } type byPriority []pixOrder func (x byPriority) Len() int { return len(x) } func (x byPriority) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byPriority) Less(i, j int) bool { return x[i].Priority > x[j].Priority } func loadSize(data []byte, max int) *image.RGBA { i, _, err := image.Decode(bytes.NewBuffer(data)) if err != nil { panic(err) } // switch i := i.(type) { // case *image.RGBA64: // i = i.RGBA() // } b := i.Bounds() dx, dy := max, max if b.Dx() > b.Dy() { dy = b.Dy() * dx / b.Dx() } else { dx = b.Dx() * dy / b.Dy() } var irgba *image.RGBA switch i := i.(type) { case *image.RGBA: irgba = qr.ResizeRGBA(i, i.Bounds(), dx, dy) case *image.NRGBA: irgba = qr.ResizeNRGBA(i, i.Bounds(), dx, dy) } return irgba } func makeTarg(data []byte, max int) [][]int { i := loadSize(data, max) b := i.Bounds() dx, dy := b.Dx(), b.Dy() targ := make([][]int, dy) arr := make([]int, dx*dy) for y := 0; y < dy; y++ { targ[y], arr = arr[:dx], arr[dx:] row := targ[y] for x := 0; x < dx; x++ { p := i.Pix[y*i.Stride+4*x:] r, g, b, a := p[0], p[1], p[2], p[3] if a == 0 { row[x] = -1 } else { row[x] = int((299*uint32(r) + 587*uint32(g) + 114*uint32(b) + 500) / 1000) } } } return targ } func newBlock(nd, nc int, rs *gf256.RSEncoder, dat, cdata []byte) *bitBlock { b := &bitBlock{ DataBytes: nd, CheckBytes: nc, B: make([]byte, nd+nc), Tmp: make([]byte, nc), RS: rs, bdata: dat, cdata: cdata, } copy(b.B, dat) rs.ECC(b.B[:nd], b.B[nd:]) b.check() if !bytes.Equal(b.Tmp, cdata) { panic("cdata") } b.M = make([][]byte, nd*8) for i := range b.M { row := make([]byte, nd+nc) b.M[i] = row for j := range row { row[j] = 0 } row[i/8] = 1 << (7 - uint(i%8)) rs.ECC(row[:nd], row[nd:]) } return b } func pngEncode(c image.Image) []byte { var b bytes.Buffer png.Encode(&b, c) return b.Bytes() } func addDither(pixByOff []pixinfo, pix coding.Pixel, err int) { if pix.Role() != coding.Data && pix.Role() != coding.Check { return } pinfo := &pixByOff[pix.Offset()] println("add", pinfo.X, pinfo.Y, pinfo.DTarg, err) pinfo.DTarg += err } // Image generates the pretty qr code type Image struct { Target [][]int Dx int Dy int URL string Tag string Version int Mask int Scale int Rotation int Size int // RandControl says to pick the pixels randomly. RandControl bool Seed int64 // Dither says to dither instead of using threshold pixel layout. Dither bool // OnlyDataBits says to use only data bits, not check bits. OnlyDataBits bool // Code is the final QR code. Code *qr.Code // Control is a PNG showing the pixels that we controlled. // Pixels we don't control are grayed out. SaveControl bool Control []byte } func (m *Image) target(x, y int) (targ byte, contrast int) { tx := x + m.Dx ty := y + m.Dy if ty < 0 || ty >= len(m.Target) || tx < 0 || tx >= len(m.Target[ty]) { return 255, -1 } v0 := m.Target[ty][tx] if v0 < 0 { return 255, -1 } targ = byte(v0) n := 0 sum := 0 sumsq := 0 const del = 5 for dy := -del; dy <= del; dy++ { for dx := -del; dx <= del; dx++ { if 0 <= ty+dy && ty+dy < len(m.Target) && 0 <= tx+dx && tx+dx < len(m.Target[ty+dy]) { v := m.Target[ty+dy][tx+dx] sum += v sumsq += v * v n++ } } } avg := sum / n contrast = sumsq/n - avg*avg return } func (m *Image) rotate(p *coding.Plan, rot int) { if rot == 0 { return } N := len(p.Pixel) pix := make([][]coding.Pixel, N) apix := make([]coding.Pixel, N*N) for i := range pix { pix[i], apix = apix[:N], apix[N:] } switch rot { case 0: // ok case 1: for y := 0; y < N; y++ { for x := 0; x < N; x++ { pix[y][x] = p.Pixel[x][N-1-y] } } case 2: for y := 0; y < N; y++ { for x := 0; x < N; x++ { pix[y][x] = p.Pixel[N-1-y][N-1-x] } } case 3: for y := 0; y < N; y++ { for x := 0; x < N; x++ { pix[y][x] = p.Pixel[N-1-x][y] } } } p.Pixel = pix } // Encode encodes func (m *Image) Encode() error { p, err := coding.NewPlan(coding.Version(m.Version), coding.L, coding.Mask(m.Mask)) if err != nil { return err } m.rotate(p, m.Rotation) // QR parameters. nd := p.DataBytes / p.Blocks nc := p.CheckBytes / p.Blocks extra := p.DataBytes - nd*p.Blocks rs := gf256.NewRSEncoder(coding.Field, nc) // Build information about pixels, indexed by data/check bit number. pixByOff := make([]pixinfo, (p.DataBytes+p.CheckBytes)*8) expect := make([][]bool, len(p.Pixel)) for y, row := range p.Pixel { expect[y] = make([]bool, len(row)) for x, pix := range row { targ, contrast := m.target(x, y) if m.RandControl && contrast >= 0 { contrast = rand.Intn(128) + 64*((x+y)%2) + 64*((x+y)%3%2) } expect[y][x] = pix&coding.Black != 0 if r := pix.Role(); r == coding.Data || r == coding.Check { pixByOff[pix.Offset()] = pixinfo{X: x, Y: y, Pix: pix, Targ: targ, Contrast: contrast} } } } Again: // Count fixed initial data bits, prepare template URL. url := m.URL + "#" var b coding.Bits coding.String(url).Encode(&b, p.Version) coding.Num("").Encode(&b, p.Version) bbit := b.Bits() dbit := p.DataBytes*8 - bbit if dbit < 0 { return fmt.Errorf("cannot encode URL into available bits") } num := make([]byte, dbit/10*3) for i := range num { num[i] = '0' } b.Pad(dbit) b.Reset() coding.String(url).Encode(&b, p.Version) coding.Num(num).Encode(&b, p.Version) b.AddCheckBytes(p.Version, p.Level) data := b.Bytes() doff := 0 // data offset coff := 0 // checksum offset mbit := bbit + dbit/10*10 // Choose pixels. bitblocks := make([]*bitBlock, p.Blocks) for blocknum := 0; blocknum < p.Blocks; blocknum++ { if blocknum == p.Blocks-extra { nd++ } bdata := data[doff/8 : doff/8+nd] cdata := data[p.DataBytes+coff/8 : p.DataBytes+coff/8+nc] bb := newBlock(nd, nc, rs, bdata, cdata) bitblocks[blocknum] = bb // Determine which bits in this block we can try to edit. lo, hi := 0, nd*8 if lo < bbit-doff { lo = bbit - doff if lo > hi { lo = hi } } if hi > mbit-doff { hi = mbit - doff if hi < lo { hi = lo } } // Preserve [0, lo) and [hi, nd*8). for i := 0; i < lo; i++ { if !bb.canSet(uint(i), (bdata[i/8]>>uint(7-i&7))&1) { return fmt.Errorf("cannot preserve required bits") } } for i := hi; i < nd*8; i++ { if !bb.canSet(uint(i), (bdata[i/8]>>uint(7-i&7))&1) { return fmt.Errorf("cannot preserve required bits") } } // Can edit [lo, hi) and checksum bits to hit target. // Determine which ones to try first. order := make([]pixOrder, (hi-lo)+nc*8) for i := lo; i < hi; i++ { order[i-lo].Off = doff + i } for i := 0; i < nc*8; i++ { order[hi-lo+i].Off = p.DataBytes*8 + coff + i } if m.OnlyDataBits { order = order[:hi-lo] } for i := range order { po := &order[i] po.Priority = pixByOff[po.Off].Contrast<<8 | rand.Intn(256) } sort.Sort(byPriority(order)) const mark = false for i := range order { po := &order[i] pinfo := &pixByOff[po.Off] bval := pinfo.Targ if bval < 128 { bval = 1 } else { bval = 0 } pix := pinfo.Pix if pix&coding.Invert != 0 { bval ^= 1 } if pinfo.HardZero { bval = 0 } var bi int if pix.Role() == coding.Data { bi = po.Off - doff } else { bi = po.Off - p.DataBytes*8 - coff + nd*8 } if bb.canSet(uint(bi), bval) { pinfo.Block = bb pinfo.Bit = uint(bi) if mark { p.Pixel[pinfo.Y][pinfo.X] = coding.Black } } else { if pinfo.HardZero { panic("hard zero") } if mark { p.Pixel[pinfo.Y][pinfo.X] = 0 } } } bb.copyOut() const cheat = false for i := 0; i < nd*8; i++ { pinfo := &pixByOff[doff+i] pix := p.Pixel[pinfo.Y][pinfo.X] if bb.B[i/8]&(1<= 128 { // want white pval = 0 v = 255 } bval := pval // bit value if pix&coding.Invert != 0 { bval ^= 1 } if pinfo.HardZero && bval != 0 { bval ^= 1 pval ^= 1 v ^= 255 } // Set pixel value as we want it. pinfo.Block.reset(pinfo.Bit, bval) _, _ = x, y err := targ - v if x+1 < len(row) { addDither(pixByOff, row[x+1], err*7/16) } if false && y+1 < len(p.Pixel) { if x > 0 { addDither(pixByOff, p.Pixel[y+1][x-1], err*3/16) } addDither(pixByOff, p.Pixel[y+1][x], err*5/16) if x+1 < len(row) { addDither(pixByOff, p.Pixel[y+1][x+1], err*1/16) } } } } for _, bb := range bitblocks { bb.copyOut() } } noops := 0 // Copy numbers back out. for i := 0; i < dbit/10; i++ { // Pull out 10 bits. v := 0 for j := 0; j < 10; j++ { bi := uint(bbit + 10*i + j) v <<= 1 v |= int((data[bi/8] >> (7 - bi&7)) & 1) } // Turn into 3 digits. if v >= 1000 { // Oops - too many 1 bits. // We know the 512, 256, 128, 64, 32 bits are all set. // Pick one at random to clear. This will break some // checksum bits, but so be it. // println("oops", i, v) pinfo := &pixByOff[bbit+10*i+3] // TODO random pinfo.Contrast = 1e9 >> 8 pinfo.HardZero = true noops++ } num[i*3+0] = byte(v/100 + '0') num[i*3+1] = byte(v/10%10 + '0') num[i*3+2] = byte(v%10 + '0') } if noops > 0 { goto Again } var b1 coding.Bits coding.String(url).Encode(&b1, p.Version) coding.Num(num).Encode(&b1, p.Version) b1.AddCheckBytes(p.Version, p.Level) if !bytes.Equal(b.Bytes(), b1.Bytes()) { fmt.Printf("mismatch\n%d %x\n%d %x\n", len(b.Bytes()), b.Bytes(), len(b1.Bytes()), b1.Bytes()) panic("byte mismatch") } cc, err := p.Encode(coding.String(url), coding.Num(num)) if err != nil { return err } if !m.Dither { for y, row := range expect { for x, pix := range row { if cc.Black(x, y) != pix { println("mismatch", x, y, p.Pixel[y][x].String()) } } } } m.Code = &qr.Code{Bitmap: cc.Bitmap, Size: cc.Size, Stride: cc.Stride, Scale: m.Scale} if m.SaveControl { // m.Control = pngEncode(makeImage(req, "", "", 0, cc.Size, 4, m.Scale, func(x, y int) (rgba uint32) { // pix := p.Pixel[y][x] // if pix.Role() == coding.Data || pix.Role() == coding.Check { // pinfo := &pixByOff[pix.Offset()] // if pinfo.Block != nil { // if cc.Black(x, y) { // return 0x000000ff // } // return 0xffffffff // } // } // if cc.Black(x, y) { // return 0x3f3f3fff // } // return 0xbfbfbfff // })) } return nil } qart-0.1/qart.go000066400000000000000000000062511272322417500136300ustar00rootroot00000000000000package qart import ( "fmt" "io/ioutil" "image" "image/color" "image/png" "os" "bytes" "github.com/vitrun/qart/qr" ) // grayScale turn the image into white and black func grayScale(src image.Image) *image.Gray{ bounds := src.Bounds() w, h := bounds.Max.X, bounds.Max.Y gray := image.NewGray(bounds) for x := 0; x < w; x++ { for y := 0; y < h; y++ { oldColor := src.At(x, y) grayColor := color.GrayModel.Convert(oldColor) gray.Set(x, y, grayColor) } } return gray } // convert2PNG convert any format to PNG func convert2PNG(i image.Image) bytes.Buffer{ // Convert image to 128x128 gray+alpha. // i := grayScale(i) b := i.Bounds() const max = 128 // If it's gigantic, it's more efficient to downsample first // and then resize; resizing will smooth out the roughness. var i1 *image.RGBA if b.Dx() > 4*max || b.Dy() > 4*max { w, h := 2*max, 2*max if b.Dx() > b.Dy() { h = b.Dy() * h / b.Dx() } else { w = b.Dx() * w / b.Dy() } i1 = qr.Resample(i, b, w, h) } else { // "Resample" to same size, just to convert to RGBA. i1 = qr.Resample(i, b, b.Dx(), b.Dy()) } b = i1.Bounds() // Encode to PNG. dx, dy := 128, 128 if b.Dx() > b.Dy() { dy = b.Dy() * dx / b.Dx() } else { dx = b.Dx() * dy / b.Dy() } i128 := qr.ResizeRGBA(i1, i1.Bounds(), dx, dy) var buf bytes.Buffer if err := png.Encode(&buf, i128); err != nil { panic(err) } return buf } //InitImage prepares the image func InitImage(src []byte, seed int64, version, scale, mask, x, y int, randCtrl, dither, onlyData, saveCtrl bool) *Image{ size, rotate := 0, 0 if version > 8 { version = 8 } if scale == 0 { scale = 8 } if version >= 12 && scale >= 4 { scale /= 2 } decodedImg, _, err := image.Decode(bytes.NewBuffer(src)) if err != nil { return nil } buf := convert2PNG(decodedImg) target := makeTarg(buf.Bytes(), 17+4*version+size) img := &Image{ Dx: x, Dy: y, URL: "", Version: version, Mask: mask, RandControl: randCtrl, Dither: dither, OnlyDataBits: onlyData, SaveControl: saveCtrl, Scale: scale, Target: target, Seed: seed, Rotation: rotate, Size: size, } return img } // EncodeUrl encodes the url to the prepared image func EncodeUrl(url string, img *Image) []byte { img.URL = url if err := img.Encode(); err != nil { fmt.Printf("error: %s\n", err) return nil } var dat []byte switch { case img.SaveControl: dat = img.Control default: dat = img.Code.PNG() } return dat } // Encode encodes a string with an image as the background func Encode(url string, src []byte, seed int64, version, scale, mask, x, y int, randCtrl, dither, onlyData, saveCtrl bool) []byte { img := InitImage(src, seed, version, scale, mask, x, y, randCtrl, dither, onlyData, saveCtrl) return EncodeUrl(url, img) } // EncodeByFile encodes the given url with a specific image func EncodeByFile(url, srcImg, dstImg string, version int) { data, err := ioutil.ReadFile(srcImg) if err != nil { fmt.Printf("err: %s\n", err) return } dst := Encode(url, data, 879633355, version, 4, 2, 4, 4, false, false, false, false) ioutil.WriteFile(dstImg, dst, (os.FileMode)(0644)) } qart-0.1/qart_test.go000066400000000000000000000011721272322417500146640ustar00rootroot00000000000000/** * Copyright ©2014-04-07 Alex */ package qart import ( "bytes" "image/png" "io/ioutil" "fmt" "os" "testing" ) // ReadWrite test func ReadWrite() { data, err := ioutil.ReadFile("/tmp/in.png") if err != nil { fmt.Printf("err: %s\n", err) return } i := loadSize(data, 48) var buf bytes.Buffer png.Encode(&buf, i) ioutil.WriteFile("/tmp/out.png", buf.Bytes(), (os.FileMode)(0644)) fmt.Printf("Hello world!") } // Image test func TestEncodeByFile(t *testing.T) { srcImg := "/tmp/in.png" dstImg := "/tmp/out.png" url := "http://www.baidu.com/" EncodeByFile(url, srcImg, dstImg, 8) } qart-0.1/qr/000077500000000000000000000000001272322417500127505ustar00rootroot00000000000000qart-0.1/qr/png.go000066400000000000000000000207541272322417500140730ustar00rootroot00000000000000// 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.bsd file. package qr // PNG writer for QR codes. import ( "bytes" "encoding/binary" "hash" "hash/crc32" ) // PNG returns a PNG image displaying the code. // // PNG uses a custom encoder tailored to QR codes. // Its compressed size is about 2x away from optimal, // but it runs about 20x faster than calling png.Encode // on c.Image(). func (c *Code) PNG() []byte { var p pngWriter return p.encode(c) } type pngWriter struct { tmp [16]byte wctmp [4]byte buf bytes.Buffer zlib bitWriter crc hash.Hash32 } var pngHeader = []byte("\x89PNG\r\n\x1a\n") func (w *pngWriter) encode(c *Code) []byte { scale := c.Scale siz := c.Size w.buf.Reset() // Header w.buf.Write(pngHeader) // Header block binary.BigEndian.PutUint32(w.tmp[0:4], uint32((siz+8)*scale)) binary.BigEndian.PutUint32(w.tmp[4:8], uint32((siz+8)*scale)) w.tmp[8] = 1 // 1-bit w.tmp[9] = 0 // gray w.tmp[10] = 0 w.tmp[11] = 0 w.tmp[12] = 0 w.writeChunk("IHDR", w.tmp[:13]) // Comment w.writeChunk("tEXt", comment) // Data w.zlib.writeCode(c) w.writeChunk("IDAT", w.zlib.bytes.Bytes()) // End w.writeChunk("IEND", nil) return w.buf.Bytes() } var comment = []byte("Software\x00QR-PNG http://qr.swtch.com/") func (w *pngWriter) writeChunk(name string, data []byte) { if w.crc == nil { w.crc = crc32.NewIEEE() } binary.BigEndian.PutUint32(w.wctmp[0:4], uint32(len(data))) w.buf.Write(w.wctmp[0:4]) w.crc.Reset() copy(w.wctmp[0:4], name) w.buf.Write(w.wctmp[0:4]) w.crc.Write(w.wctmp[0:4]) w.buf.Write(data) w.crc.Write(data) crc := w.crc.Sum32() binary.BigEndian.PutUint32(w.wctmp[0:4], crc) w.buf.Write(w.wctmp[0:4]) } func (b *bitWriter) writeCode(c *Code) { const ftNone = 0 b.adler32.Reset() b.bytes.Reset() b.nbit = 0 scale := c.Scale siz := c.Size // zlib header b.tmp[0] = 0x78 b.tmp[1] = 0 b.tmp[1] += uint8(31 - (uint16(b.tmp[0])<<8+uint16(b.tmp[1]))%31) b.bytes.Write(b.tmp[0:2]) // Start flate block. b.writeBits(1, 1, false) // final block b.writeBits(1, 2, false) // compressed, fixed Huffman tables // White border. // First row. b.byte(ftNone) n := (scale*(siz+8) + 7) / 8 b.byte(255) b.repeat(n-1, 1) // 4*scale rows total. b.repeat((4*scale-1)*(1+n), 1+n) for i := 0; i < 4*scale; i++ { b.adler32.WriteNByte(ftNone, 1) b.adler32.WriteNByte(255, n) } row := make([]byte, 1+n) for y := 0; y < siz; y++ { row[0] = ftNone j := 1 var z uint8 nz := 0 for x := -4; x < siz+4; x++ { // Raw data. for i := 0; i < scale; i++ { z <<= 1 if !c.Black(x, y) { z |= 1 } if nz++; nz == 8 { row[j] = z j++ nz = 0 } } } if j < len(row) { row[j] = z } for _, z := range row { b.byte(z) } // Scale-1 copies. b.repeat((scale-1)*(1+n), 1+n) b.adler32.WriteN(row, scale) } // White border. // First row. b.byte(ftNone) b.byte(255) b.repeat(n-1, 1) // 4*scale rows total. b.repeat((4*scale-1)*(1+n), 1+n) for i := 0; i < 4*scale; i++ { b.adler32.WriteNByte(ftNone, 1) b.adler32.WriteNByte(255, n) } // End of block. b.hcode(256) b.flushBits() // adler32 binary.BigEndian.PutUint32(b.tmp[0:], b.adler32.Sum32()) b.bytes.Write(b.tmp[0:4]) } // A bitWriter is a write buffer for bit-oriented data like deflate. type bitWriter struct { bytes bytes.Buffer bit uint32 nbit uint tmp [4]byte adler32 adigest } func (b *bitWriter) writeBits(bit uint32, nbit uint, rev bool) { // reverse, for huffman codes if rev { br := uint32(0) for i := uint(0); i < nbit; i++ { br |= ((bit >> i) & 1) << (nbit - 1 - i) } bit = br } b.bit |= bit << b.nbit b.nbit += nbit for b.nbit >= 8 { b.bytes.WriteByte(byte(b.bit)) b.bit >>= 8 b.nbit -= 8 } } func (b *bitWriter) flushBits() { if b.nbit > 0 { b.bytes.WriteByte(byte(b.bit)) b.nbit = 0 b.bit = 0 } } func (b *bitWriter) hcode(v int) { /* Lit Value Bits Codes --------- ---- ----- 0 - 143 8 00110000 through 10111111 144 - 255 9 110010000 through 111111111 256 - 279 7 0000000 through 0010111 280 - 287 8 11000000 through 11000111 */ switch { case v <= 143: b.writeBits(uint32(v)+0x30, 8, true) case v <= 255: b.writeBits(uint32(v-144)+0x190, 9, true) case v <= 279: b.writeBits(uint32(v-256)+0, 7, true) case v <= 287: b.writeBits(uint32(v-280)+0xc0, 8, true) default: panic("invalid hcode") } } func (b *bitWriter) byte(x byte) { b.hcode(int(x)) } func (b *bitWriter) codex(c int, val int, nx uint) { b.hcode(c + val>>nx) b.writeBits(uint32(val)&(1<= 258+3; n -= 258 { b.repeat1(258, d) } if n > 258 { // 258 < n < 258+3 b.repeat1(10, d) b.repeat1(n-10, d) return } if n < 3 { panic("invalid flate repeat") } b.repeat1(n, d) } func (b *bitWriter) repeat1(n, d int) { /* Extra Extra Extra Code Bits Length(s) Code Bits Lengths Code Bits Length(s) ---- ---- ------ ---- ---- ------- ---- ---- ------- 257 0 3 267 1 15,16 277 4 67-82 258 0 4 268 1 17,18 278 4 83-98 259 0 5 269 2 19-22 279 4 99-114 260 0 6 270 2 23-26 280 4 115-130 261 0 7 271 2 27-30 281 5 131-162 262 0 8 272 2 31-34 282 5 163-194 263 0 9 273 3 35-42 283 5 195-226 264 0 10 274 3 43-50 284 5 227-257 265 1 11,12 275 3 51-58 285 0 258 266 1 13,14 276 3 59-66 */ switch { case n <= 10: b.codex(257, n-3, 0) case n <= 18: b.codex(265, n-11, 1) case n <= 34: b.codex(269, n-19, 2) case n <= 66: b.codex(273, n-35, 3) case n <= 130: b.codex(277, n-67, 4) case n <= 257: b.codex(281, n-131, 5) case n == 258: b.hcode(285) default: panic("invalid repeat length") } /* Extra Extra Extra Code Bits Dist Code Bits Dist Code Bits Distance ---- ---- ---- ---- ---- ------ ---- ---- -------- 0 0 1 10 4 33-48 20 9 1025-1536 1 0 2 11 4 49-64 21 9 1537-2048 2 0 3 12 5 65-96 22 10 2049-3072 3 0 4 13 5 97-128 23 10 3073-4096 4 1 5,6 14 6 129-192 24 11 4097-6144 5 1 7,8 15 6 193-256 25 11 6145-8192 6 2 9-12 16 7 257-384 26 12 8193-12288 7 2 13-16 17 7 385-512 27 12 12289-16384 8 3 17-24 18 8 513-768 28 13 16385-24576 9 3 25-32 19 8 769-1024 29 13 24577-32768 */ if d <= 4 { b.writeBits(uint32(d-1), 5, true) } else if d <= 32768 { nbit := uint(16) for d <= 1<<(nbit-1) { nbit-- } v := uint32(d - 1) v &^= 1 << (nbit - 1) // top bit is implicit code := uint32(2*nbit - 2) // second bit is low bit of code code |= v >> (nbit - 2) v &^= 1 << (nbit - 2) b.writeBits(code, 5, true) // rest of bits follow b.writeBits(uint32(v), nbit-2, false) } else { panic("invalid repeat distance") } } func (b *bitWriter) run(v byte, n int) { if n == 0 { return } b.byte(v) if n-1 < 3 { for i := 0; i < n-1; i++ { b.byte(v) } } else { b.repeat(n-1, 1) } } type adigest struct { a, b uint32 } func (d *adigest) Reset() { d.a, d.b = 1, 0 } const amod = 65521 func aupdate(a, b uint32, pi byte, n int) (aa, bb uint32) { // TODO(rsc): 6g doesn't do magic multiplies for b %= amod, // only for b = b%amod. // invariant: a, b < amod if pi == 0 { b += uint32(n%amod) * a b = b % amod return a, b } // n times: // a += pi // b += a // is same as // b += n*a + n*(n+1)/2*pi // a += n*pi m := uint32(n) b += (m % amod) * a b = b % amod b += (m * (m + 1) / 2) % amod * uint32(pi) b = b % amod a += (m % amod) * uint32(pi) a = a % amod return a, b } func afinish(a, b uint32) uint32 { return b<<16 | a } func (d *adigest) WriteN(p []byte, n int) { for i := 0; i < n; i++ { for _, pi := range p { d.a, d.b = aupdate(d.a, d.b, pi, 1) } } } func (d *adigest) WriteNByte(pi byte, n int) { d.a, d.b = aupdate(d.a, d.b, pi, n) } func (d *adigest) Sum32() uint32 { return afinish(d.a, d.b) } qart-0.1/qr/qr.go000066400000000000000000000045471272322417500137330ustar00rootroot00000000000000package qr import ( "errors" "image" "image/color" "github.com/vitrun/qart/coding" ) // 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 Encode(text string, level 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 enc coding.Encoding switch { case coding.Num(text).Check() == nil: enc = coding.Num(text) case coding.Alpha(text).Check() == nil: enc = coding.Alpha(text) default: enc = coding.String(text) } // Pick size. l := coding.Level(level) var v coding.Version for v = coding.MinVersion; ; v++ { if v > coding.MaxVersion { return nil, errors.New("text too long to encode as QR") } if enc.Bits(v) <= v.DataBytes(l)*8 { break } } // Build and execute plan. p, err := coding.NewPlan(v, l, 0) if err != nil { return nil, err } cc, err := p.Encode(enc) if err != nil { return nil, err } // TODO: Pick appropriate mask. return &Code{cc.Bitmap, cc.Size, cc.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 (c *Code) Black(x, y int) bool { return 0 <= x && x < c.Size && 0 <= y && y < c.Size && c.Bitmap[y*c.Stride+x/8]&(1< 0; { qy := dy - (py % dy) if qy > remy { qy = remy } // Spread the source pixel over 1 or more destination columns. px := uint64(x) * ww index := 4 * ((py/dy)*ww + (px / dx)) for remx := ww; remx > 0; { qx := dx - (px % dx) if qx > remx { qx = remx } qxy := qx * qy sum[index+0] += r64 * qxy sum[index+1] += g64 * qxy sum[index+2] += b64 * qxy sum[index+3] += a64 * qxy index += 4 px += qx remx -= qx } py += qy remy -= qy } } } return average(sum, w, h, (uint64)(n)) } // ResizeNRGBA returns a scaled copy of the RGBA image slice r of m. // The returned image has width w and height h. func ResizeNRGBA(m *image.NRGBA, r image.Rectangle, w, h int) *image.RGBA { ww, hh := uint64(w), uint64(h) dx, dy := uint64(r.Dx()), uint64(r.Dy()) // See comment in Resize. n, sum := dx*dy, make([]uint64, 4*w*h) for y := r.Min.Y; y < r.Max.Y; y++ { pix := m.Pix[(y-r.Min.Y)*m.Stride:] for x := r.Min.X; x < r.Max.X; x++ { // Get the source pixel. p := pix[(x-r.Min.X)*4:] r64 := uint64(p[0]) g64 := uint64(p[1]) b64 := uint64(p[2]) a64 := uint64(p[3]) r64 = (r64 * a64) / 255 g64 = (g64 * a64) / 255 b64 = (b64 * a64) / 255 // Spread the source pixel over 1 or more destination rows. py := uint64(y) * hh for remy := hh; remy > 0; { qy := dy - (py % dy) if qy > remy { qy = remy } // Spread the source pixel over 1 or more destination columns. px := uint64(x) * ww index := 4 * ((py/dy)*ww + (px / dx)) for remx := ww; remx > 0; { qx := dx - (px % dx) if qx > remx { qx = remx } qxy := qx * qy sum[index+0] += r64 * qxy sum[index+1] += g64 * qxy sum[index+2] += b64 * qxy sum[index+3] += a64 * qxy index += 4 px += qx remx -= qx } py += qy remy -= qy } } } return average(sum, w, h, (uint64)(n)) } // Resample returns a resampled copy of the image slice r of m. // The returned image has width w and height h. func Resample(m image.Image, r image.Rectangle, w, h int) *image.RGBA { if w < 0 || h < 0 { return nil } if w == 0 || h == 0 || r.Dx() <= 0 || r.Dy() <= 0 { return image.NewRGBA(image.Rect(0, 0, w, h)) } curw, curh := r.Dx(), r.Dy() img := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < h; y++ { for x := 0; x < w; x++ { // Get a source pixel. subx := x * curw / w suby := y * curh / h r32, g32, b32, a32 := m.At(subx, suby).RGBA() r := uint8(r32 >> 8) g := uint8(g32 >> 8) b := uint8(b32 >> 8) a := uint8(a32 >> 8) img.SetRGBA(x, y, color.RGBA{r, g, b, a}) } } return img }