packageutils;importjava.awt.image.BufferedImage;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStream;importorg.apache.commons.lang.StringUtils;importorg.krysalis.barcode4j.impl.code39.Code39Bean;importorg.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;importorg.krysalis.barcode4j.tools.UnitConv;/*** 条形码工具类
*
*@authortangzz
* @createDate 2015年9月17日
**/
public classBarcodeUtil {/*** 生成文件
*
*@parammsg
*@parampath
*@return
*/
public staticFile generateFile(String msg, String path) {
File file= newFile(path);try{
generate(msg,newFileOutputStream(file));
}catch(FileNotFoundException e) {throw newRuntimeException(e);
}returnfile;
}/*** 生成字节
*
*@parammsg
*@return
*/
public static byte[] generate(String msg) {
ByteArrayOutputStream ous= newByteArrayOutputStream();
generate(msg, ous);returnous.toByteArray();
}/*** 生成到流
*
*@parammsg
*@paramous*/
public static voidgenerate(String msg, OutputStream ous) {if (StringUtils.isEmpty(msg) || ous == null) {return;
}
Code39Bean bean= newCode39Bean();//精细度
final int dpi = 150;//module宽度
final double moduleWidth = UnitConv.in2mm(1.0f /dpi);//配置对象
bean.setModuleWidth(moduleWidth);
bean.setWideFactor(3);
bean.doQuietZone(false);
String format= "image/png";try{//输出到流
BitmapCanvasProvider canvas= newBitmapCanvasProvider(ous, format, dpi,
BufferedImage.TYPE_BYTE_BINARY,false, 0);//生成条形码
bean.generateBarcode(canvas, msg);//结束绘制
canvas.finish();
}catch(IOException e) {throw newRuntimeException(e);
}
}public static voidmain(String[] args) {
String msg= "123456789";
String path= "barcode.png";
generateFile(msg, path);
}
}