b665f5f5683447cd1fb57b5d391191e9c2192d91
[zxing.git] / core / src / com / google / zxing / oned / EAN8Writer.java
1 /*
2  * Copyright 2009 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.oned;
18
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.WriterException;
21 import com.google.zxing.common.ByteMatrix;
22
23 import java.util.Hashtable;
24
25 /**
26  * This object renders an EAN8 code as a ByteMatrix 2D array of greyscale
27  * values.
28  *
29  * @author aripollak@gmail.com (Ari Pollak)
30  */
31 public final class EAN8Writer extends UPCEANWriter {
32
33   private static final int codeWidth = 3 + // start guard
34       (7 * 4) + // left bars
35       5 + // middle guard
36       (7 * 4) + // right bars
37       3; // end guard
38
39   public ByteMatrix encode(String contents, BarcodeFormat format, int width, int height,
40       Hashtable hints) throws WriterException {
41     if (format != BarcodeFormat.EAN_8) {
42       throw new IllegalArgumentException("Can only encode EAN_8, but got "
43           + format);
44     }
45
46     return super.encode(contents, format, width, height, hints);
47   }
48
49   /** @return a byte array of horizontal pixels (0 = white, 1 = black) */
50   public byte[] encode(String contents) {
51     if (contents.length() != 8) {
52       throw new IllegalArgumentException(
53           "Requested contents should be 8 digits long, but got " + contents.length());
54     }
55
56     byte[] result = new byte[codeWidth];
57     int pos = 0;
58
59     pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, 1);
60
61     for (int i = 0; i <= 3; i++) {
62       int digit = Integer.parseInt(contents.substring(i, i + 1));
63       pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], 0);
64     }
65
66     pos += appendPattern(result, pos, UPCEANReader.MIDDLE_PATTERN, 0);
67
68     for (int i = 4; i <= 7; i++) {
69       int digit = Integer.parseInt(contents.substring(i, i + 1));
70       pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], 1);
71     }
72     pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, 1);
73
74     return result;
75   }
76
77 }