Java生成条形码code128
作者:互联网
生成code 128条形码工具类
maven依赖
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
gradle依赖
compile("net.sf.barcode4j:barcode4j:2.1")
工具代码
package com.tian.demo.admin.controller;
import org.apache.commons.lang.ObjectUtils;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @ClassName BarCodeUtils
* @Description TODO
* @Author Harry
* @Date 2020/5/130:35
* @Version 1.0
**/
public class BarCodeUtils {
/**
* 生成code128条形码
*
* @param height 条形码的高度
* @param width 条形码的宽度
* @param message 要生成的文本
* @param withQuietZone 是否两边留白
* @param hideText 隐藏可读文本
* @return 图片对应的字节码
*/
public static byte[] generateBarCode128(String message, Double height, Double width, boolean withQuietZone, boolean hideText) {
Code128Bean bean = new Code128Bean();
// 分辨率
int dpi = 512;
// 设置两侧是否留白
bean.doQuietZone(withQuietZone);
// 设置条形码高度和宽度
bean.setBarHeight((double) ObjectUtils.defaultIfNull(height, 9.0D));
if (width != null) {
bean.setModuleWidth(width);
}
// 设置文本位置(包括是否显示)
if (hideText) {
bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
}
// 设置图片类型
String format = "image/png";
ByteArrayOutputStream ous = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
BufferedImage.TYPE_BYTE_BINARY, false, 0);
// 生产条形码
bean.generateBarcode(canvas, message);
try {
canvas.finish();
} catch (IOException e) {
}
return ous.toByteArray();
}
}
控制层调用
@GetMapping("test")
public void test(HttpServletRequest request,HttpServletResponse response) throws IOException {
String parameter = request.getParameter("");
byte[] bytes = BarCodeUtils.generateBarCode128("4305383450594", 10.00, 0.3, true, false);
response.setContentType("image/png");
OutputStream output = response.getOutputStream();
InputStream in = new ByteArrayInputStream(bytes);
int len;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) != -1) {
output.write(buf, 0, len);
}
output.flush();
//如果没有下面两行,可能出现getOutputStream() has already been called for this response的异常
// output.clear();
// out = pageContext.pushBody();
// Result result = new Result();
}
1如果觉得本文对你有帮助,欢迎点赞,欢迎关注我,如果有补充欢迎评论交流,我将努力创作更多更好的文章。
标签:条形码,Java,code128,param,bean,barcode4j,new,import 来源: https://blog.csdn.net/wutian842929/article/details/106108723