我尝试使用这种方式生成随机 ean-8 条码。我已经生成了从 10000000 到 99999999 的随机数来为 ean-8 代码生成随机的 8 位数字。它给了我一个错误。
Exception in thread "main" java.lang.IllegalArgumentException: Checksum is bad (1). Expected: 7
at org.krysalis.barcode4j.impl.upcean.EAN8LogicImpl.handleChecksum(EAN8LogicImpl.java:85)
at org.krysalis.barcode4j.impl.upcean.EAN8LogicImpl.generateBarcodeLogic(EAN8LogicImpl.java:102)
at org.krysalis.barcode4j.impl.upcean.UPCEANBean.generateBarcode(UPCEANBean.java:93)
at org.krysalis.barcode4j.impl.ConfigurableBarcodeGenerator.generateBarcode(ConfigurableBarcodeGenerator.java:174)
at barcode2.BARCODE2.main(BARCODE2.java:42)
Java Result: 1
这是代码。
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.krysalis.barcode4j.BarcodeException;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
public class BARCODE2 {
public static void main(String[] args) throws ConfigurationException, BarcodeException, IOException {
BarcodeUtil util = BarcodeUtil.getInstance();
BarcodeGenerator gen = util.createBarcodeGenerator(buildCfg("ean-8"));
OutputStream fout = new FileOutputStream("ean-8.jpg");
int resolution = 200;
BitmapCanvasProvider canvas = new BitmapCanvasProvider(
fout, "image/jpeg", resolution, BufferedImage.TYPE_BYTE_BINARY, false, 0);
int min = 10000000;
int max = 99999999;
Random r = new Random();
int randomnumber = r.nextInt(max - min + 1) + min;
String barcodecods = String.valueOf(randomnumber);
gen.generateBarcode(canvas, barcodecods);
canvas.finish();
}
private static Configuration buildCfg(String type) {
DefaultConfiguration cfg = new DefaultConfiguration("barcode");
//Bar code type
DefaultConfiguration child = new DefaultConfiguration(type);
cfg.addChild(child);
//Human readable text position
DefaultConfiguration attr = new DefaultConfiguration("human-readable");
DefaultConfiguration subAttr = new DefaultConfiguration("placement");
subAttr.setValue("bottom");
attr.addChild(subAttr);
child.addChild(attr);
return cfg;
}
}
但是当将我用于随机代码的字符串值替换为特定的 8 位数字时,程序运行正常。我应该怎么办?我哪里做错了?是否有任何其他方法可以为 ean-8 条形码生成生成随机 8 位数字?