条码的生成我们使用的是barcode4j这个包,但我们要注意的是条码有很多种,有些条码只能是数字,而有些条码能带字母和数字还有可能是一些特殊符号。
这里我们主要是测试怎么生成带字母的条码。
```java
/**
* 生成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,double fontSize) {
Code128Bean bean = new Code128Bean();
// 分辨率
int dpi = 512;
// 设置两侧是否留白
bean.doQuietZone(withQuietZone);
bean.setFontSize(fontSize);
// 设置条形码高度和宽度
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) {
//ByteArrayOutputStream won't happen
}
return ous.toByteArray();
}
=====================================================================================================================
上面的代码就是生成128的条码代码,这里有几点要注意。
1)怎么设置条码的高度和宽度。
2)怎么设置是否显示文本,而且怎么设置文本大小,
3)怎么设置文本的位置。