本文共 6219 字,大约阅读时间需要 20 分钟。
慕课网有对应课程,可以参考着看一下:https://www.imooc.com/learn/531
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.29</version> </dependency>
其中core和javase是必须要的,fastjson是需要用到里面json转化时才需要的,可以根据需要觉得是否添加。@Test public void testEncode() throws WriterException, IOException { String filePath = "D://"; String fileName = "code.png"; String content = "http://www.baidu.com";// 内容 int width = 200; // 图像宽度 int height = 200; // 图像高度 String format = "png";// 图像类型 Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵 Path path = FileSystems.getDefault().getPath(filePath, fileName); MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像 System.out.println("输出成功."); }
这里直接写了一个测试类,只需要引入core-3.0.0.jar、javase-3.0.0.jar这两个jar,二维码的内容就是"http://www.baidu.com",如果是网址,用浏览器扫描之后就会自动跳转到对应网站,图片是输出到D盘根目录下面的code.png,图片大小和高度也是可以设置的。 /** * 生成二维码 * @param response * @param content * @throws WriterException * @throws IOException */ @RequestMapping("/createQrCode") public void generateQrcode(HttpServletResponse response,String content) throws WriterException, IOException{ int width = 190; // 图像宽度 int height = 190; // 图像高度 String format = "png";// 图像类型 Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵 MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream()); }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>二维码生成测试页面</title></head><body><h2>Hello World!</h2> <%-- <jsp:include page="../common_easyUI.jsp"></jsp:include> --%><script type="text/javascript" src="${pageContext.request.contextPath}/plugins/jquery-easyui-1.5.3/jquery.min.js"></script> <p>Enter Text to create QR Code</p> <input id="content" type="text" value="www.baidu.com"> <input value="Generate QR Code" type="submit"> <div style="width: 150px; height: 150px;" > <img id="codei"></img> </div></body><script type="text/javascript">$(function(){ var content=$("#content").val(); document.getElementById("codei").src="${pageContext.request.contextPath}/do/createQrCode?content="+content})</script></html>
这样就可以根据业务需求在页面动态生成二维码了。demo下载链接:
package com.cn.control.qrcode;import java.awt.Color;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.swetake.util.Qrcode;/** * 生成二维码图片 * * @param content */@Controllerpublic class QrCodeUtils { @RequestMapping("/createQrCode") public static void createQrCode(String content,HttpServletResponse response) { try { Qrcode qrcode = new Qrcode(); // 设置二维码排错率, L(7%)、M(15%)、Q(25%)、H(30%) 排错率越高可存储的信息越少,但对二维码的清晰度要求比较低 qrcode.setQrcodeErrorCorrect('M'); // N代表数字,A代表字符a-Z,B代表其他字符 qrcode.setQrcodeEncodeMode('B'); // 设置二维码版本,取值范围为0-40,值越大尺寸越大,存储的信息越大 qrcode.setQrcodeVersion(7); // 设置图片高宽度 BufferedImage bufferedImage = new BufferedImage(139, 139, BufferedImage.TYPE_INT_RGB); // 创建一个 Graphics2D,画图 Graphics2D gs = bufferedImage.createGraphics(); // 设置图片的背景色 gs.setBackground(Color.WHITE); gs.clearRect(0, 0, 139, 139); // 设置图片颜色 gs.setColor(Color.black); // 将输出内容转为byte类型 byte[] contentBytes = content.getBytes("utf-8"); // 设置偏移量,不设置可能导致解析出错 int pixoff = 2; // 输出内容 if (contentBytes.length > 0 && contentBytes.length < 130) { 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 { System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,130 ]. "); return; } // 没有logo的二维码// gs.dispose(); bufferedImage.flush(); ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); //生成图片输出流中 // 生成二维码QRCode图片// File imgFile = new File("D:/qrCode/1.jpg"); // 生成的图片在D盘下,名为 qrCode.png// ImageIO.write(bufferedImage, "png", imgFile); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) {// createQrCode("www.baidu.com"); }}