Java生成條形碼code128(親測有效)
阿新 • • 發佈:2020-05-17
生成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,len); } output.flush(); //如果沒有下面兩行,可能出現getOutputStream() has already been called for this response的異常 // output.clear(); // out = pageContext.pushBody(); // Result result = new Result(); }
到此這篇關於Java生成條形碼code128(親測有效)的文章就介紹到這了,更多相關Java生成條形碼code128內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!