You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ZXing Java库生成UPC/EAN条码时抛出IllegalArgumentException异常,求解决方法

解决ZXing生成EAN/UPC条码时的参数异常问题

哈哈,这个坑我之前也踩过!咱们先看报错信息:Can only encode QR_CODE, but got EAN_13,这个提示其实已经说得很清楚了——你用的QRCodeWriter是专门用来生成QR二维码的,它根本不支持EAN_13、UPC这类一维条码格式,所以才会抛出参数异常。

正确的解决思路

ZXing库提供了两种方式来生成EAN/UPC这类一维条码:

  • 使用**MultiFormatWriter**:它是一个通用的条码写入器,支持ZXing所有支持的条码格式(包括QR、EAN_13、UPC-A等),适合需要灵活切换条码类型的场景;
  • 使用对应格式的专用Writer:比如生成EAN_13就用EAN13Writer,生成UPC-A就用UPCAWriter,这种方式更针对性,避免格式混淆。

修改后的代码示例

方式1:用MultiFormatWriter生成EAN_13条码

String textToCodify = "1234567891234"; // EAN_13需要12或13位字符串(12位会自动计算校验位)
MultiFormatWriter barcodeWriter = new MultiFormatWriter();
BitMatrix bitMatrix = barcodeWriter.encode(textToCodify, BarcodeFormat.EAN_13, 300, 100); // 一维条码建议宽高比调整为3:1左右
File outputfile = new File("ean13_barcode.jpg");
BufferedImage code = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(code, "jpg", outputfile);

方式2:用EAN13Writer生成EAN_13条码

String textToCodify = "1234567891234";
EAN13Writer barcodeWriter = new EAN13Writer();
BitMatrix bitMatrix = barcodeWriter.encode(textToCodify, BarcodeFormat.EAN_13, 300, 100);
File outputfile = new File("ean13_barcode.jpg");
BufferedImage code = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(code, "jpg", outputfile);

额外注意事项

  • EAN_13的输入字符串长度必须是12位或13位:如果是12位,ZXing会自动计算并添加第13位校验码;如果是13位,会自动校验是否符合规则,不符合会抛出异常;
  • 一维条码的宽高比建议设置为3:1左右(比如300x100),这样生成的条码更符合标准,扫码识别率更高。

内容的提问来源于stack exchange,提问作者Nabil Berrehouma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:17:27