Move GridSampler into common package and refactor to ready it for use with Data Matrix
[zxing.git] / core / src / com / google / zxing / common / DefaultGridSampler.java
1 /*
2  * Copyright 2007 Google Inc.
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.common;
18
19 import com.google.zxing.MonochromeBitmapSource;
20 import com.google.zxing.ReaderException;
21
22 /**
23  * @author srowen@google.com (Sean Owen)
24  */
25 public final class DefaultGridSampler extends GridSampler {
26
27   public BitMatrix sampleGrid(MonochromeBitmapSource image,
28                               int dimension,
29                               float p1ToX, float p1ToY,
30                               float p2ToX, float p2ToY,
31                               float p3ToX, float p3ToY,
32                               float p4ToX, float p4ToY,
33                               float p1FromX, float p1FromY,
34                               float p2FromX, float p2FromY,
35                               float p3FromX, float p3FromY,
36                               float p4FromX, float p4FromY) throws ReaderException {
37
38     PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(
39         p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY,
40         p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);
41
42     BitMatrix bits = new BitMatrix(dimension);
43     float[] points = new float[dimension << 1];
44     for (int i = 0; i < dimension; i++) {
45       int max = points.length;
46       float iValue = (float) i + 0.5f;
47       for (int j = 0; j < max; j += 2) {
48         points[j] = (float) (j >> 1) + 0.5f;
49         points[j + 1] = iValue;
50       }
51       transform.transformPoints(points);
52       // Quick check to see if points transformed to something inside the image;
53       // sufficent to check the endpoints
54       checkEndpoint(image, points);
55       for (int j = 0; j < max; j += 2) {
56         if (image.isBlack((int) points[j], (int) points[j + 1])) {
57           // Black(-ish) pixel
58           bits.set(i, j >> 1);
59         }
60       }
61     }
62     return bits;
63   }
64
65 }