bfe97bc8d93d32f47f96a23782ad171a73d091ce
[zxing.git] / javase / src / com / google / zxing / client / j2se / BufferedImageMonochromeBitmapSource.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.client.j2se;
18
19 import com.google.zxing.BlackPointEstimationMethod;
20 import com.google.zxing.MonochromeBitmapSource;
21 import com.google.zxing.ReaderException;
22 import com.google.zxing.common.BitArray;
23 import com.google.zxing.common.BlackPointEstimator;
24
25 import java.awt.geom.AffineTransform;
26 import java.awt.image.AffineTransformOp;
27 import java.awt.image.BufferedImage;
28 import java.awt.image.BufferedImageOp;
29
30 /**
31  * <p>An implementation based upon {@link BufferedImage}. This provides access to the
32  * underlying image as if it were a monochrome image. Behind the scenes, it is evaluating
33  * the luminance of the underlying image by retrieving its pixels' RGB values.</p>
34  *
35  * <p>This may also be used to construct a {@link MonochromeBitmapSource}
36  * based on a region of a {@link BufferedImage}; see
37  * {@link #BufferedImageMonochromeBitmapSource(BufferedImage, int, int, int, int)}.</p>
38  *
39  * @author srowen@google.com (Sean Owen), Daniel Switkin (dswitkin@google.com)
40  */
41 public final class BufferedImageMonochromeBitmapSource implements MonochromeBitmapSource {
42
43   private final BufferedImage image;
44   private final int left;
45   private final int top;
46   private final int width;
47   private final int height;
48   private int blackPoint;
49   private BlackPointEstimationMethod lastMethod;
50   private int lastArgument;
51
52   private static final int LUMINANCE_BITS = 5;
53   private static final int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
54   private static final int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
55
56   public BufferedImageMonochromeBitmapSource(BufferedImage image) {
57     this(image, 0, 0, image.getWidth(), image.getHeight());
58   }
59
60   public BufferedImageMonochromeBitmapSource(BufferedImage image, int left, int top, int right, int bottom) {
61     this.image = image;
62     blackPoint = 0x7F;
63     lastMethod = null;
64     lastArgument = 0;
65     int sourceHeight = image.getHeight();
66     int sourceWidth = image.getWidth();
67     if (left < 0 || top < 0 || right >= sourceWidth || bottom >= sourceHeight || right <= left || bottom <= top) {
68       throw new IllegalArgumentException("Invalid bounds: (" + top + ',' + left + ") (" + right + ',' + bottom + ')');
69     }
70     this.left = left;
71     this.top = top;
72     this.width = right - left;
73     this.height = bottom - top;
74   }
75
76   /**
77    * @return underlying {@link BufferedImage} behind this instance. Note that even if this instance
78    *  only uses a subset of the full image, the returned value here represents the entire backing image.
79    */
80   public BufferedImage getImage() {
81     return image;
82   }
83
84   private int getRGB(int x, int y) {
85     return image.getRGB(left + x, top + y);
86   }
87
88   private void getRGBRow(int startX, int startY, int[] result) {
89     image.getRGB(left + startX, top + startY, result.length, 1, result, 0, result.length);
90   }
91
92   public boolean isBlack(int x, int y) {
93     return computeRGBLuminance(getRGB(x, y)) < blackPoint;
94   }
95
96   public BitArray getBlackRow(int y, BitArray row, int startX, int getWidth) {
97     if (row == null) {
98       row = new BitArray(getWidth);
99     } else {
100       row.clear();
101     }
102     int[] pixelRow = new int[getWidth];
103     getRGBRow(startX, y, pixelRow);
104     for (int i = 0; i < getWidth; i++) {
105       if (computeRGBLuminance(pixelRow[i]) < blackPoint) {
106         row.set(i);
107       }
108     }
109     return row;
110   }
111
112   public int getHeight() {
113     return height;
114   }
115
116   public int getWidth() {
117     return width;
118   }
119
120   public void estimateBlackPoint(BlackPointEstimationMethod method, int argument) throws ReaderException {
121     if (!method.equals(lastMethod) || argument != lastArgument) {
122       int[] histogram = new int[LUMINANCE_BUCKETS];
123       if (method.equals(BlackPointEstimationMethod.TWO_D_SAMPLING)) {
124         int minDimension = width < height ? width : height;
125         int startI = height == minDimension ? 0 : (height - width) >> 1;
126         int startJ = width == minDimension ? 0 : (width - height) >> 1;
127         for (int n = 0; n < minDimension; n++) {
128           int pixel = getRGB(startJ + n, startI + n);
129           histogram[computeRGBLuminance(pixel) >> LUMINANCE_SHIFT]++;
130         }
131       } else if (method.equals(BlackPointEstimationMethod.ROW_SAMPLING)) {
132         if (argument < 0 || argument >= height) {
133           throw new IllegalArgumentException("Row is not within the image: " + argument);
134         }
135         int[] rgbArray = new int[width];
136         getRGBRow(0, argument, rgbArray);
137         for (int x = 0; x < width; x++) {
138           histogram[computeRGBLuminance(rgbArray[x]) >> LUMINANCE_SHIFT]++;
139         }
140       } else {
141         throw new IllegalArgumentException("Unknown method: " + method);
142       }
143       blackPoint = BlackPointEstimator.estimate(histogram) << LUMINANCE_SHIFT;
144       lastMethod = method;
145       lastArgument = argument;
146     }
147   }
148
149   public BlackPointEstimationMethod getLastEstimationMethod() {
150     return lastMethod;
151   }
152
153   public MonochromeBitmapSource rotateCounterClockwise() {
154     if (!isRotateSupported()) {
155       throw new IllegalStateException("Rotate not supported");
156     }
157     int sourceWidth = image.getWidth();
158     int sourceHeight = image.getHeight();
159     // 90 degrees counterclockwise:
160     AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
161     BufferedImageOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
162     // Note width/height are flipped since we are rotating 90 degrees:
163     BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, image.getType());
164     op.filter(image, rotatedImage);
165     return new BufferedImageMonochromeBitmapSource(rotatedImage,
166                                                    top,
167                                                    sourceWidth - (left + width),
168                                                    top + height,
169                                                    sourceWidth - left);
170   }
171
172   public boolean isRotateSupported() {
173     // Can't run AffineTransforms on images of unknown format
174     return image.getType() != BufferedImage.TYPE_CUSTOM;
175   }
176
177   /**
178    * Extracts luminance from a pixel from this source. By default, the source is assumed to use RGB,
179    * so this implementation computes luminance is a function of a red, green and blue components as
180    * follows:
181    *
182    * <code>Y = 0.299R + 0.587G + 0.114B</code>
183    *
184    * where R, G, and B are values in [0,1].
185    */
186   private static int computeRGBLuminance(int pixel) {
187     // Coefficients add up to 1024 to make the divide into a fast shift
188     return (306 * ((pixel >> 16) & 0xFF) +
189         601 * ((pixel >> 8) & 0xFF) +
190         117 * (pixel & 0xFF)) >> 10;
191   }
192
193 }