Java生成条形码(亲测可通过扫码枪扫出) 您所在的位置:网站首页 货物识别码扫描怎么弄 Java生成条形码(亲测可通过扫码枪扫出)

Java生成条形码(亲测可通过扫码枪扫出)

2024-07-17 17:25| 来源: 网络整理| 查看: 265

背景

项目上对接美国的外卖平台Uber(可以理解为国内的美团),需要在打印的小票上生成一个条形码,供Uber的骑手扫码取货。经过一顿百度发现,大佬们提供的条形码要么扫不出来,要么就很不美观(长宽比不合适),于是就自己摸索了一把。

代码 1、Maven依赖 net.sf.barcode4j barcode4j-light 2.0 2、工具类 /** * 生成条码工具类 */ public class BarcodeUtils { /** * 生成条形码文件 * * @param msg 条形码的文本内容 * @param path 生成条形码的文件路径 * @return */ public static File generateFile(String msg, String path) { File file = new File(path); OutputStream outputStream = null; try { outputStream = new FileOutputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } try { generateBarCode128(msg, 10.0, 0.3, true, false, outputStream); } catch (Exception e) { throw new RuntimeException(e); } return file; } /** * 生成code128条形码 * * @param message 要生成的文本 * @param height 条形码的高度 * @param width 条形码的宽度 * @param withQuietZone 是否两边留白 * @param hideText 隐藏可读文本 * @param outputStream 输出流 */ public static void generateBarCode128(String message, Double height, Double width, boolean withQuietZone, boolean hideText, OutputStream outputStream) { Code128Bean bean = new Code128Bean(); // 分辨率,越大条形码就越大 int dpi = 150; // 设置两侧是否留白 bean.doQuietZone(withQuietZone); // 设置条形码高度和宽度 bean.setBarHeight(ObjectUtils.defaultIfNull(height, 9.0D)); if (width != null) { bean.setModuleWidth(width); } // 设置文本位置(包括是否显示) if (hideText) { bean.setMsgPosition(HumanReadablePlacement.HRP_NONE); } // 设置图片类型 String format = "image/png"; BitmapCanvasProvider canvas = new BitmapCanvasProvider(outputStream, format, dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0); // 生产条形码 bean.generateBarcode(canvas, message); try { canvas.finish(); } catch (IOException e) { //ByteArrayOutputStream won't happen } } public static void main(String[] args) { String msg = "TRO2022032300000400301"; String path = "barcode2.png"; generateFile(msg, path); } } 3、效果图

请添加图片描述

4、关于条形码的编码

上述工具类给出的条形码编码为:Code128; 如果向使用其他编码,只需要在generateBarCode128()方法中将Code128Bean换成需要的,比如:Code39Bean; 在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有