Code128Bean 生成条码图片输出Base64或地址值

Code128Bean 生成Base64图片返回给前端:

首先需要导入依赖 gradle:

implementation 'net.sf.barcode4j:barcode4j-light:2.0'

barCode 为想要生成的条码号

public static String generateBarCode(String barCode) {
		String fileName = null;
		if (StringUtils.isEmpty(barCode)) {
			return null;
		}
		ByteArrayOutputStream os=null;

		// 如果想要其他类型的条码(CODE 39, EAN-8...)直接获取相关对象Code39Bean...
		Code128Bean bean = new Code128Bean();
		// 分辨率:值越大条码越长,分辨率越高
		final int dpi = 512;
		// 设置两侧是否加空白
		bean.doQuietZone(true);

		final double modouleWidth = UnitConv.in2mm(3.0f / dpi);
		bean.setModuleWidth(modouleWidth);
		bean.setBarHeight(5);
		// bean.setFontSize(3);
		// bean.setHeight(6);

		// 设置文本位置(包括是否显示)
		bean.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);
		// 设置图片类型
		String format = "image/png";
		try {
			os = new ByteArrayOutputStream();
			// 输出到流
			BitmapCanvasProvider canvas = new BitmapCanvasProvider(os, format, dpi, BufferedImage.TYPE_BYTE_BINARY,
					false, 0);
			// 生成条形码
			bean.generateBarcode(canvas, barCode);
			// 结束绘制
			canvas.finish();
			byte[] bytes = os.toByteArray();
			return Base64Utils.encodeToString(bytes);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (os != null)
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

Code128Bean 生成条码图片返回地址值

public static String generateBarCode(String barCode) {
		String fileName = null;
		if (StringUtils.isEmpty(barCode)) {
			return null;
		}
		FileOutputStream out = null;

		// 如果想要其他类型的条码(CODE 39, EAN-8...)直接获取相关对象Code39Bean...
		Code128Bean bean = new Code128Bean();
		// 分辨率:值越大条码越长,分辨率越高
		final int dpi = 512;
		// 设置两侧是否加空白
		bean.doQuietZone(true);

		final double modouleWidth = UnitConv.in2mm(3.0f / dpi);
		bean.setModuleWidth(modouleWidth);
		bean.setBarHeight(5);
		// bean.setFontSize(3);
		// bean.setHeight(6);

		// 设置文本位置(包括是否显示)
		bean.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);
		// 设置图片类型
		String format = "image/png";
		try {
            //图片存放路径
			fileName = Constants.BAR_CODE_ABS_PATH + barCode + ".png";
			File file = new File(fileName);
			out = new FileOutputStream(file);
			// 输出到流
			BitmapCanvasProvider canvas = new BitmapCanvasProvider(out, format, dpi, BufferedImage.TYPE_BYTE_BINARY,false, 0);
			// 生成条形码
			bean.generateBarcode(canvas, barCode);
			// 结束绘制
			canvas.finish();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return fileName;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值