1、将要使用到的jar包导入项目(1、commons-lang-2.3.jar 2、barcode4j-light-2.0.jar)
2、新建类 BarcodeUtil
3、代码部分
package com.sale.util;
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.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
/**
*
* @author Saffi
* @date 2017年10月6日
*/
public class BarcodeUtil {
/**
* 生成文件
*
* @param msg
* @param path
* @return
*/
public File generateFiles(String msg, String path) {
File file = new File(path);
try {
generates(msg, new FileOutputStream(file));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
return file;
}
/**
* 生成字节
*
* @param msg
* @return
* @throws IOException
*/
public byte[] generates(String msg) throws IOException {
ByteArrayOutputStream ous = new ByteArrayOutputStream();
generates(msg, ous);
ous.close();
return ous.toByteArray();
}
/**
* 生成到流
*
* @param msg
* @param ous
*/
public static void generates(String msg, OutputStream ous) {
if (StringUtils.isEmpty(msg) || ous == null) {
return;
}
// 条形码类型
//Code39Bean bean = new Code39Bean();
Code128Bean bean = new Code128Bean();
// 精细度
final int dpi = 150;
// module宽度
final double moduleWidth = UnitConv.in2mm(2.0f / dpi);
// 配置对象
bean.setModuleWidth(moduleWidth);
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();
ous.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
4、调用接口
/**
* 生成条形码
* @author Saffi
* @throws IOException
*/
@RequestMapping("testOrderBarcodes.action")
public @ResponseBody String testOrderBarcodes(HttpServletResponse respon) throws IOException {
String result="error";
try {
//调用接口
BarcodeUtil util = new BarcodeUtil();
//条码内容
String msg = ‘Te123456‘;
//路径
String path ="C:/Users/Administrator/Desktop/barcode/barcode"+msg+".png";
util.generateFiles(msg, path);
result="succ";
} catch (Exception e) {
e.printStackTrace();
respon.sendRedirect("error.action");
log.error("系统错误", e.fillInStackTrace());
}
return result;
}