Slightly friendlier error message
[zxing.git] / core / src / com / google / zxing / MultiFormatReader.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;
18
19 import com.google.zxing.qrcode.QRCodeReader;
20 import com.google.zxing.upc.UPCReader;
21
22 import java.util.Hashtable;
23
24 /**
25  * <p>This implementation can detect barcodes in one of several formats within
26  * an image, and then decode what it finds. This implementation supports all
27  * barcode formats that this library supports.</p>
28  *
29  * @author srowen@google.com (Sean Owen), dswitkin@google.com (Daniel Switkin)
30  */
31 public final class MultiFormatReader implements Reader {
32
33   public Result decode(MonochromeBitmapSource image) throws ReaderException {
34     return decode(image, null);
35   }
36
37   public Result decode(MonochromeBitmapSource image, Hashtable hints)
38       throws ReaderException {
39     Hashtable possibleFormats = hints == null ? null : (Hashtable) hints.get(DecodeHintType.POSSIBLE_FORMATS);
40
41     boolean tryUPC;
42     boolean tryQR;
43     if (possibleFormats == null) {
44       tryUPC = true;
45       tryQR = true;
46     } else {
47       tryUPC = possibleFormats.contains(BarcodeFormat.UPC);
48       tryQR = possibleFormats.contains(BarcodeFormat.QR_CODE);
49     }
50     if (!(tryUPC || tryQR)) {
51       throw new ReaderException("POSSIBLE_FORMATS specifies no supported types");
52     }
53
54     // Save the last exception as what we'll report if nothing decodes
55     ReaderException savedRE = null;
56
57     // UPC is much faster to decode, so try it first.
58     if (tryUPC) {
59       try {
60         return new UPCReader().decode(image, hints);
61       } catch (ReaderException re) {
62         savedRE = re;
63       }
64     }
65     
66     // Then fall through to QR codes.
67     if (tryQR) {
68       try {
69         return new QRCodeReader().decode(image, hints);
70       } catch (ReaderException re) {
71         savedRE = re;
72       }
73     }
74     
75     throw savedRE;
76   }
77
78 }