二维码生成

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.swetake.util.Qrcode;

/**
 * Servlet implementation class QrCode
 */
public class QrCode extends HttpServlet {
 private static final long serialVersionUID = 1L;

 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  this.doPost(request, response);
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("image/jpeg");
  String codeName = request.getParameter("transactionNo");
  Qrcode qrcode = new Qrcode();
  qrcode.setQrcodeErrorCorrect('M');
  qrcode.setQrcodeEncodeMode('B');
  qrcode.setQrcodeVersion(7);
  byte[] d = codeName.getBytes("UTF-8");
  BufferedImage bi = new BufferedImage(139, 139, BufferedImage.TYPE_INT_RGB);
  Graphics2D g = bi.createGraphics();
  g.setBackground(Color.WHITE);
  g.clearRect(0, 0, 139, 139);
  g.setColor(Color.BLACK);
  if (d.length > 0 && d.length < 123) {
   boolean[][] b = qrcode.calQrcode(d);
   for (int i = 0; i < b.length; i++) {
    for (int j = 0; j < b.length; j++) {
     if (b[j][i]) {
      g.fillRect(j * 3 + 2, i * 3 + 2, 3, 3);
     }
    }
   }
  }
  // 生成图片
  g.dispose();
  // 向客户端返回二进制的响应,需要OutputStream
  OutputStream os = response.getOutputStream();
  // jpeg 代表图片格式
  ImageIO.write(bi, "jpg", os);
  os.flush();
 }

}


 

你可能感兴趣的:(二维码)