package cn.com.do1.wechat.common;import java.awt.Color;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletResponse;import com.swetake.util.Qrcode;/** java生成二维码工具类扫一扫*/public class QrcodeUtil {/*** 生成二维码图像** @author sss* @param content* 需要生成二维码的文字或者其他内容* 生成二维码图像保存的地址* @return*/public static void QrcodeImg(String content, HttpServletResponse response) {int width = 160;int height = 160;// 实例化Qrcodetry {Qrcode qrcode = new Qrcode();// 设置二维码排错率,可以选项L(%7),M(%15),Q(%25),H(%30)qrcode.setQrcodeErrorCorrect('M');qrcode.setQrcodeEncodeMode('B');// 设置二维码的尺寸,取值范围(1-40)qrcode.setQrcodeVersion(8);// 设置图片尺寸BufferedImage bufImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);// 绘制二维码图片Graphics2D gs = bufImg.createGraphics();// 设置二维码的背景颜色gs.setBackground(Color.WHITE);// 创建二维码的矩形区域gs.clearRect(0, 0, width, height);// 设置二维码的颜色gs.setColor(Color.BLACK);//设置偏移量 不设置可能导致解析出错int pixoff = 2;// 获取内容的字节数组,设置编码集byte[] contentBytes = new byte[2048];contentBytes = content.getBytes("utf-8");if (contentBytes.length > 0 && contentBytes.length < 1000) {boolean[][] codeOut = qrcode.calQrcode(contentBytes);for (int i = 0; i < codeOut.length; i++) {for (int j = 0; j < codeOut.length; j++) {if (codeOut[j][i]) {gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);}}}} else {throw new RuntimeException("输入的内容超出了二维码的最大限制值");}gs.dispose();bufImg.flush();//生成二维码QRCode图片 (以流的方式输出。)ImageIO.write(bufImg, "jpg", response.getOutputStream());// // 生成二维码图片// File imgFile = new File(imgPath);// ImageIO.write(bufImg, "png", imgFile);// System.out.println("恭喜您,二维码生成成功");} catch (Exception e) {e.printStackTrace();}}}
注:加大二维码的图片Vesion可以容纳更多的字节
int width = 160; int height = 160; // 实例化Qrcode try { Qrcode qrcode = new Qrcode(); // 设置二维码排错率,可以选项L(%7),M(%15),Q(%25),H(%30) qrcode.setQrcodeErrorCorrect('M'); qrcode.setQrcodeEncodeMode('B'); // 设置二维码的尺寸,取值范围(1-40) qrcode.setQrcodeVersion(8);