2 * Copyright 2010 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.oned;
19 import java.util.Hashtable;
20 import com.google.zxing.BarcodeFormat;
21 import com.google.zxing.WriterException;
22 import com.google.zxing.common.BitMatrix;
25 * This object renders a CODE128 code as a {@link BitMatrix}.
27 * @author erik.barbara@gmail.com (Erik Barbara)
29 public final class Code128Writer extends UPCEANWriter {
31 public BitMatrix encode(String contents,
35 Hashtable hints) throws WriterException {
36 if (format != BarcodeFormat.CODE_128) {
37 throw new IllegalArgumentException("Can only encode CODE_128, but got " + format);
39 return super.encode(contents, format, width, height, hints);
42 public byte[] encode(String contents) {
43 int length = contents.length();
45 throw new IllegalArgumentException(
46 "Requested contents should be less than 80 digits long, but got " + length);
49 int codeWidth = 11 + 11 + 13; //start plus check plus stop character
50 //get total code width for this barcode
51 for (int i = 0; i < length; i++) {
52 int[] patterns = Code128Reader.CODE_PATTERNS[contents.charAt(i) - ' '];
53 for (int j = 0; j < patterns.length; j++) {
54 codeWidth += patterns[j];
57 byte[] result = new byte[codeWidth];
58 int pos = appendPattern(result, 0, Code128Reader.CODE_PATTERNS[104], 1);
60 //append next character to bytematrix
61 for(int i = 0; i < length; i++) {
62 check += (contents.charAt(i) - ' ') * (i + 1);
63 pos += appendPattern(result, pos, Code128Reader.CODE_PATTERNS[contents.charAt(i) - ' '],1);
65 //compute checksum and append it along with end character and quiet space
67 pos += appendPattern(result,pos,Code128Reader.CODE_PATTERNS[check],1);
68 pos += appendPattern(result,pos,Code128Reader.CODE_PATTERNS[106],1);