简体   繁体   中英

How to generate random barcode code using barcode4j?

I've tried to generating random ean-8 barcodes using this way. I've generated random numbers from 10000000 to 99999999 to produce random 8 digit numbers for ean-8 codes. It gives me an error of this.

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

here's the code.

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;
}
}

But when replacing the string value I used for random code into specific 8 digit numbers the program runs properly. What should I do? Where did I go wrong? Is there any other way of generating random 8 digit numbers for ean-8 barcode generation?

Bar codes are not just simple numbers. The entire number contains a check-digit, which is generated from the other digits by an arithmetic procedure. Thus, not all numbers are valid bar codes.

Different barcodes use different check-digit algorithms. You need to find out which algorithm is expected by the library you're using, and then generate barcodes that satisfy this requirement.

So, for example, if the barcode is 8 digits you would generate random 7-digit numbers and append the correct calculated 8th digit to make a valid barcode.

Note: A check-digit is the decimal equivalent of a parity bit. It allows software to detect if the code was read incorrectly in most cases. It isn't perfect, as there are some errors that would produce the same check digit, but it greatly reduces the likelihood of a mis-read.

Generate a random number with 7 digits, and add the check-digit with the following method:

public static int checkdigit(String idWithoutCheckdigit) {

    // allowable characters within identifier
    String validChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVYWXZ_";

    // remove leading or trailing whitespace, convert to uppercase
    idWithoutCheckdigit = idWithoutCheckdigit.trim().toUpperCase();

    // this will be a running total
    int sum = 0;

    // loop through digits from right to left
    for (int i = 0; i < idWithoutCheckdigit.length(); i++) {

        // set ch to "current" character to be processed
        char ch = idWithoutCheckdigit.charAt(idWithoutCheckdigit.length() - i - 1);

        // throw exception for invalid characters
        if (validChars.indexOf(ch) == -1)
            throw new RuntimeException("\"" + ch + "\" is an invalid character");

        // our "digit" is calculated using ASCII value - 48
        int digit = ch - 48;

        // weight will be the current digit's contribution to
        // the running total
        int weight;
        if (i % 2 == 0) {

            // for alternating digits starting with the rightmost, we
            // use our formula this is the same as multiplying x 2 and
            // adding digits together for values 0 to 9. Using the
            // following formula allows us to gracefully calculate a
            // weight for non-numeric "digits" as well (from their
            // ASCII value - 48).
            weight = (2 * digit) - (digit / 5) * 9;

        } else {

            // even-positioned digits just contribute their ascii
            // value minus 48
            weight = digit;

        }

        // keep a running total of weights
        sum += weight;

    }
    // avoid sum less than 10 (if characters below "0" allowed,
    // this could happen)
    sum = Math.abs(sum) + 10;
    // check digit is amount needed to reach next number
    // divisible by ten
    return (10 - (sum % 10)) % 10;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM