背景
目前二維碼的應用場景已經遍布各類互聯網平台,通常是將產品/商品的唯一編號存儲於二維碼中以做掃碼識別。
而用於生產環境的條形碼技術仍然存在,如硬件設備制造、供應、物流運輸等等。
在常見的產品信息管理、物料訂單系統中,存在多個生成及打印條形碼(一維碼)的需求場景。
解決方案
Java生成條形碼的方案 -- barcode4j、zxing
barcode4j
barcode4j開源Java條形碼生成庫。支持多種編碼格式,比如:code-39,code-128等
zxing
是由google開源的1D/2D編解碼類庫。目標是能夠對QR編碼、Data Matrix、UPC的1D條形碼進行解碼。 其提供了多種平台下的客戶端包括:J2ME、J2SE和Android
本次采用了barcode4j作為解決方案
環境准備
下載barcode4j-light
barcode4j 依賴的lib包略顯臃腫,其中包括了avalon-framework/servelet-api,
因此本次選擇的是輕量級的版本barcode4j-light
maven地址
<dependency> <groupId>net.sf.barcode4j</groupId> <artifactId>barcode4j-light</artifactId> <version>2.0</version> </dependency>
//另外,也可以下載barcode4j-bin包
代碼實例
BarcodeUtil工具類
package utils; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.lang.StringUtils; import org.krysalis.barcode4j.impl.code39.Code39Bean; import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider; import org.krysalis.barcode4j.tools.UnitConv; /** * 條形碼工具類 * * @author tangzz * @createDate 2015年9月17日 * */ public class BarcodeUtil { /** * 生成文件 * * @param msg * @param path * @return */ public static File generateFile(String msg, String path) { File file = new File(path); try { generate(msg, new FileOutputStream(file)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } return file; } /** * 生成字節 * * @param msg * @return */ public static byte[] generate(String msg) { ByteArrayOutputStream ous = new ByteArrayOutputStream(); generate(msg, ous); return ous.toByteArray(); } /** * 生成到流 * * @param msg * @param ous */ public static void generate(String msg, OutputStream ous) { if (StringUtils.isEmpty(msg) || ous == null) { return; } Code39Bean bean = new Code39Bean(); // 精細度 final int dpi = 150; // module寬度 final double moduleWidth = UnitConv.in2mm(1.0f / dpi); // 配置對象 bean.setModuleWidth(moduleWidth); bean.setWideFactor(3); bean.doQuietZone(false); String format = "image/png"; try { // 輸出到流 BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0); // 生成條形碼 bean.generateBarcode(canvas, msg); // 結束繪制 canvas.finish(); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) { String msg = "123456789"; String path = "barcode.png"; generateFile(msg, path); } }
FAQ
二維碼相對於條形碼的優勢
數據容量更大;超越了字母數字的限制;具有抗損毀能力
關於條形碼的各種編碼格式


如何生成或識別二維碼
推薦使用ZXing項目 https://github.com/zxing/zxing