Initial checkin of bug client code from buglabs
[zxing.git] / bug / src / com / google / zxing / client / bug / AWTImageMonochromeBitmapSource.java
1 /*
2  * Copyright 2008 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.client.bug;
18
19 import com.google.zxing.ReaderException;
20 import com.google.zxing.common.BaseMonochromeBitmapSource;
21
22 import java.awt.Image;
23 import java.awt.image.PixelGrabber;
24
25 /**
26  * <p>An implementation based on AWT's {@link Image} representation.
27  * This can be used on CDC devices or other devices that do not have access to the
28  * Mobile Information Device Profile and thus do not have access to
29  * javax.microedition.lcdui.Image.</p>
30  *
31  * @author David Albert
32  * @author Sean Owen
33  */
34 public final class AWTImageMonochromeBitmapSource extends BaseMonochromeBitmapSource {
35
36   private final int height;
37   private final int width;
38   private final int[] pixels;
39
40   public AWTImageMonochromeBitmapSource(Image image) throws ReaderException {
41     height = image.getHeight(null);
42     width = image.getWidth(null);
43     pixels = new int[height * width];
44     // Seems best in this situation to grab all pixels upfront. Grabbing any individual pixel
45     // entails creating a relatively expensive object and calling through several methods.
46     PixelGrabber grabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
47     try {
48       grabber.grabPixels();
49     } catch (InterruptedException ie) {
50       throw new ReaderException("Interrupted while reading pixels");
51     }
52   }
53
54   public int getHeight() {
55     return height;
56   }
57
58   public int getWidth() {
59     return width;
60   }
61
62   /**
63    * See <code>com.google.zxing.client.j2me.LCDUIImageMonochromeBitmapSource</code> for more explanation
64    * of the computation used in this method.
65    */
66   public int getLuminance(int x, int y) {
67     int pixel = pixels[x * width + y];
68     return (((pixel & 0x00FF0000) >> 16) +
69             ((pixel & 0x0000FF00) >>  7) +
70              (pixel & 0x000000FF       )) >> 2;
71   }
72
73   public void cacheRowForLuminance(int y) {
74     // do nothing; we are already forced to cache all pixels
75   }
76
77 }