java生产条形码
准备:jbarcode-0.2.8.jar,下载地址:jbarcode-0.2.8.zip
jsp:
<img src="<%=basePath%>barcode/showBarCode" alt="" style="width: 200px; height: 150px;">
controller
import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import util.OneBarcodeUtil; @Controller @RequestMapping("/barcode") public class BarcodeController { @RequestMapping("/") public String index(){ return "barcode"; } @RequestMapping("/showBarCode") public void showIMG(HttpServletRequest req,HttpServletResponse resp) throws Exception{ OneBarcodeUtil obu = new OneBarcodeUtil(); byte[] bs = obu.createBarcodeDefault("123123123");//这里是条码号 InputStream in = new ByteArrayInputStream(bs);// 业务逻辑取得图片的byte[] BufferedOutputStream bout = new BufferedOutputStream(resp.getOutputStream()); //从输入流到输出流 try { // byte b[] = new byte[1024]; int len = in.read(bs); while (len > 0) { bout.write(bs, 0, len); len = in.read(bs); } } catch (Exception e) { throw e; } finally { bout.close(); in.close(); } } }
工具类
import java.awt.image.BufferedImage; import java.io.IOException; import java.lang.reflect.Constructor; import org.jbarcode.JBarcode; import org.jbarcode.encode.BarcodeEncoder; import org.jbarcode.encode.Code39Encoder; import org.jbarcode.paint.BaseLineTextPainter; import org.jbarcode.paint.EAN13TextPainter; import org.jbarcode.paint.WideRatioCodedPainter; import org.jbarcode.paint.WidthCodedPainter; import org.jbarcode.util.ImageUtil; public class OneBarcodeUtil { /** * 生成一维码 * @param value 值 * @return */ public static byte[] createBarcodeDefault(String value){ return createBarcode(Code39Encoder.class,value,false); } //产生一维码图片 public static byte[] createBarcode(Class<?> clazz,String value,boolean checkDigit){ try{ JBarcode localJBarcode = new JBarcode(getInstance(clazz),WidthCodedPainter.getInstance(),EAN13TextPainter.getInstance()); localJBarcode.setPainter(WideRatioCodedPainter.getInstance()); localJBarcode.setTextPainter(BaseLineTextPainter.getInstance()); localJBarcode.setCheckDigit(checkDigit); localJBarcode.setShowCheckDigit(checkDigit); return getBytes(localJBarcode.createBarcode(value)); }catch (Exception e) { e.printStackTrace(); return null; } } //获取单例的对象 private static BarcodeEncoder getInstance(Class<?> clazz) throws Exception{ Constructor<?>[] constructors=clazz.getDeclaredConstructors(); Constructor<?> privateConstructor = constructors[0]; privateConstructor.setAccessible(true); return (BarcodeEncoder)privateConstructor.newInstance(); } //获取图片字节码数组 private static byte[] getBytes(BufferedImage paramBufferedImage) throws IOException{ return ImageUtil.encode(paramBufferedImage,"jpeg", 96, 96); } }
启动项目访问:http://localhost:8080/wxPublic/barcode/
生产条形码:
本文来自博客园,作者:每天都要学一点,欢迎讨论和转载,转载请注明原文链接:https://www.cnblogs.com/yanan7890/p/8875300.html