一、添加jar依赖
1.maven方式
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
注:查询maven依赖可至网站Maven Repository
2.jar方式
将core-3.3.0.jar(或其他版本jar)拷贝至项目中
注:core-3.3.0.jar下载地址:链接:https://pan.baidu.com/s/172P7Fa3dsiU0lvRcPU9nkg 密码:xjxx
二、代码
(一)JSP页面
1.HTML
<img src="tBSPostRiskController.do?buildQrCode&download=false" /><br/>
<button type="button" onclick="download()">
二维码下载
</button>
<h3 id="tip"></h3>
2.JS(jquery)
<script>
function download() {
$.ajax({
url:"tBSPostRiskController.do?buildQrCode&download=true",
type:"post",
success:function (data) {
$("#tip").html("文件下载成功!请至\"C:/AddressQrCode/\"目录下查看");
}
});
}
</script>
(二) 后台Controller
1.二维码工具类QrCodeCreateUtil.java
public class QrCodeCreateUtil {
public static void createQrCodeWeb(OutputStream outputStream, String content,HttpServletResponse response,HttpServletRequest request) throws WriterException, IOException {
//转换字符,避免中文乱码问题
content = new String(content.getBytes("UTF-8"),"ISO-8859-1");
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 矫错级别
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 900, 900, hintMap);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(900, 900, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// 使用比特矩阵画并保存图像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++){
for (int j = 0; j < matrixWidth; j++){
if (byteMatrix.get(i, j)){
graphics.fillRect(i, j, 1, 1);
}
}
}
/*判断是否下载*/
if(request.getParameter("download").equals("true")){
File f=new File("C:/AddressQrCode/风险点.png");
File folder = f.getParentFile();
if(!folder.exists()){
folder.mkdirs();
}
ImageIO.write(image, "png",f);
}else{
ImageIO.write(image, "JPEG", outputStream);
}
}
}
2.Controller
@Scope("prototype")
@Controller
@RequestMapping("/tBSPostRiskController")
public class TBSPostRiskController {
@RequestMapping(params = "buildQrCode")
@ResponseBody
public void buildQrCode(OutputStream outputStream, String content, Integer qrCodeSize, String imageFormat,HttpServletResponse response,HttpServletRequest request) throws WriterException, IOException{
QrCodeCreateUtil.createQrCodeWeb(outputStream,"40289f67593ece2101593f25430600ef-南屯煤矿-7708工作面",response,request);
}
}
三、效果图
-------------------------------------
作者:Guo Teng
主页:https://molln.github.io/
邮箱:519843007@qq.com
转载请注明出处