此文是通过QRcode来生成二维码。
需要引入的jar包是 Qrcode_swetake.jar qrcode.jar
很多时候需要通过前端传入一些参数到后台,然后后台生成这些参数的二维码图片发送到前端展示在div中。
前端代码
//这个是需要展示二维码的div
<div class="QRcode">
</div>
<button type="button" onclick="showQRCode()">生成二维码</button>
function showQRCode() {
//obj为需要传递的参数的内容。
var obj = "12";
//为div画入img图片。src为地址。会调用action,然后生成图片。
$(".QRcode").html("<img src='showQRCode?obj=" + obj + "'/>");
}
JAVA代码
//生成图片的action
@RequestMapping(value="/showQRCode")
public void showQRCode(HttpServletResponse response, String obj) throws Exception{
//生成BufferedImage用来存放二维码
BufferedImage qrcodeImg = CreateQRCodeImg.getQrcodeImg("http://localhost:8080/show.action?qrcodeId="+obj);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(qrcodeImg, "gif", baos);
ByteArrayInputStream is = new ByteArrayInputStream(baos.toByteArray());
int size =is.available(); //得到文件大小
byte data[]=new byte[size];
is.read(data); //读数据
is.close();
response.setContentType("image/gif"); //设置返回的文件类型
OutputStream os = response.getOutputStream();
os.write(data);
os.flush();
os.close();
}
//生成二维码的方法
public static BufferedImage getQrcodeImg(String content) {
int width = 140;
int height = 140;
// 实例化Qrcode
Qrcode qrcode = new Qrcode();
// 设置二维码的排错率L(7%) M(15%) Q(25%) H(35%)
qrcode.setQrcodeErrorCorrect('M');
qrcode.setQrcodeEncodeMode('B');
// 设置二维码尺寸(1~49)
qrcode.setQrcodeVersion(7);
// 设置图片尺寸
BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
// 绘制二维码图片
Graphics2D gs = bufImg.createGraphics();
// 设置二维码背景颜色
gs.setBackground(Color.WHITE);
// 创建一个矩形区域
gs.clearRect(0, 0, width, height);
// 设置二维码的图片颜色值 黑色
gs.setColor(Color.BLACK);
// 获取内容的字节数组,设置编码集
try {
byte[] contentBytes = content.getBytes("utf-8");
int pixoff = 2;
// 输出二维码
if (contentBytes.length > 0 && contentBytes.length < 125) {
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);
}
}
}
}
gs.dispose();
bufImg.flush();
return bufImg;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
上面 getQrcodeImg() 方法中,如果传入的参数 content 长度过大的话,就需要改变相应的 qrcode.setQrcodeVersion(7);这个方法的参数。参数越大,能生成的二维码字符串长度越长。
但是个人觉得如果字符串过长的话,生成的二维码也是不好看,个人建议,不如创建一张sql表,用来存字符串内容,二维码就存简单的url和sql表的 id 即可。