Pure-barcode mode can now deal with asymmetric borders instead of assuming it's pure...
[zxing.git] / core / src / com / google / zxing / datamatrix / DataMatrixReader.java
1 /*
2  * Copyright 2007 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.datamatrix;
18
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.BinaryBitmap;
21 import com.google.zxing.ChecksumException;
22 import com.google.zxing.DecodeHintType;
23 import com.google.zxing.FormatException;
24 import com.google.zxing.NotFoundException;
25 import com.google.zxing.Reader;
26 import com.google.zxing.Result;
27 import com.google.zxing.ResultMetadataType;
28 import com.google.zxing.ResultPoint;
29 import com.google.zxing.common.BitMatrix;
30 import com.google.zxing.common.DecoderResult;
31 import com.google.zxing.common.DetectorResult;
32 import com.google.zxing.datamatrix.decoder.Decoder;
33 import com.google.zxing.datamatrix.detector.Detector;
34
35 import java.util.Hashtable;
36
37 /**
38  * This implementation can detect and decode Data Matrix codes in an image.
39  *
40  * @author bbrown@google.com (Brian Brown)
41  */
42 public final class DataMatrixReader implements Reader {
43
44   private static final ResultPoint[] NO_POINTS = new ResultPoint[0];
45   
46   private final Decoder decoder = new Decoder();
47
48   /**
49    * Locates and decodes a Data Matrix code in an image.
50    *
51    * @return a String representing the content encoded by the Data Matrix code
52    * @throws NotFoundException if a Data Matrix code cannot be found
53    * @throws FormatException if a Data Matrix code cannot be decoded
54    * @throws ChecksumException if error correction fails
55    */
56   public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException {
57     return decode(image, null);
58   }
59
60   public Result decode(BinaryBitmap image, Hashtable hints)
61       throws NotFoundException, ChecksumException, FormatException {
62     DecoderResult decoderResult;
63     ResultPoint[] points;
64     if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
65       BitMatrix bits = extractPureBits(image.getBlackMatrix());
66       decoderResult = decoder.decode(bits);
67       points = NO_POINTS;
68     } else {
69       DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect();
70       decoderResult = decoder.decode(detectorResult.getBits());
71       points = detectorResult.getPoints();
72     }
73     Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.DATAMATRIX);
74     if (decoderResult.getByteSegments() != null) {
75       result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.getByteSegments());
76     }
77     if (decoderResult.getECLevel() != null) {
78       result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.getECLevel().toString());
79     }
80     return result;
81   }
82
83   public void reset() {
84     // do nothing
85   }
86
87   /**
88    * This method detects a Data Matrix code in a "pure" image -- that is, pure monochrome image
89    * which contains only an unrotated, unskewed, image of a Data Matrix code, with some white border
90    * around it. This is a specialized method that works exceptionally fast in this special
91    * case.
92    *
93    * @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix) 
94    */
95   private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {
96
97     int height = image.getHeight();
98     int width = image.getWidth();
99     int minDimension = Math.min(height, width);
100
101     // And then keep tracking across the top-left black module to determine module size
102     //int moduleEnd = borderWidth;
103     int[] leftTopBlack = image.getTopLeftOnBit();
104     if (leftTopBlack == null) {
105       throw NotFoundException.getNotFoundInstance();
106     }
107     int x = leftTopBlack[0];
108     int y = leftTopBlack[1];
109     while (x < minDimension && y < minDimension && image.get(x, y)) {
110       x++;
111     }
112     if (x == minDimension) {
113       throw NotFoundException.getNotFoundInstance();
114     }
115
116     int moduleSize = x - leftTopBlack[0];
117
118     // And now find where the rightmost black module on the first row ends
119     int rowEndOfSymbol = width - 1;
120     while (rowEndOfSymbol >= 0 && !image.get(rowEndOfSymbol, y)) {
121       rowEndOfSymbol--;
122     }
123     if (rowEndOfSymbol < 0) {
124       throw NotFoundException.getNotFoundInstance();
125     }
126     rowEndOfSymbol++;
127
128     // Make sure width of barcode is a multiple of module size
129     if ((rowEndOfSymbol - x) % moduleSize != 0) {
130       throw NotFoundException.getNotFoundInstance();
131     }
132     int dimension = 2 + ((rowEndOfSymbol - x) / moduleSize);
133
134     y += moduleSize;
135     
136     // Push in the "border" by half the module width so that we start
137     // sampling in the middle of the module. Just in case the image is a
138     // little off, this will help recover.
139     x -= moduleSize >> 1;
140     y -= moduleSize >> 1;
141
142     if ((x + (dimension - 1) * moduleSize) >= width ||
143         (y + (dimension - 1) * moduleSize) >= height) {
144       throw NotFoundException.getNotFoundInstance();
145     }
146
147     // Now just read off the bits
148     BitMatrix bits = new BitMatrix(dimension);
149     for (int i = 0; i < dimension; i++) {
150       int iOffset = y + i * moduleSize;
151       for (int j = 0; j < dimension; j++) {
152         if (image.get(x + j * moduleSize, iOffset)) {
153           bits.set(j, i);
154         }
155       }
156     }
157     return bits;
158   }
159
160 }