spring boot使用zxing 二维码应用
Posted yqj234
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot使用zxing 二维码应用相关的知识,希望对你有一定的参考价值。
1.在POM.XML文件添加引用ZXING
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
2. 编写一个工具类QR,代码如下,直接贴上代码
package com.myapp.util;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码工具类
*
*/
public class QrCodeUtil {
//编码格式,采用utf-8
private static final String UNICODE = "utf-8";
//图片格式
private static final String FORMAT = "JPG";
//二维码宽度像素pixels数量
private static final int QRCODE_WIDTH = 300;
//二维码高度像素pixels数量
private static final int QRCODE_HEIGHT = 300;
//LOGO宽度像素pixels数量
private static final int LOGO_WIDTH = 100;
//LOGO高度像素pixels数量
private static final int LOGO_HEIGHT = 100;
//生成二维码图片
//content 二维码内容
//logoPath logo图片地址
private static BufferedImage createImage(String content, String logoPath) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, UNICODE);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (logoPath == null || "".equals(logoPath)) {
return image;
}
// 插入图片
QrCodeUtil.insertImage(image, logoPath);
return image;
}
//在图片上插入LOGO
//source 二维码图片内容
//logoPath LOGO图片地址
private static void insertImage(BufferedImage source, String logoPath) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
throw new Exception("logo file not found.");
}
Image src = ImageIO.read(new File(logoPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (width > LOGO_WIDTH) {
width = LOGO_WIDTH;
}
if (height > LOGO_HEIGHT) {
height = LOGO_HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_WIDTH - width) / 2;
int y = (QRCODE_HEIGHT - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
//生成带logo的二维码图片,保存到指定的路径
// content 二维码内容
// logoPath logo图片地址
// destPath 生成图片的存储路径
public static String save(String content, String logoPath, String destPath) throws Exception {
BufferedImage image = QrCodeUtil.createImage(content, logoPath);
File file = new File(destPath);
String path = file.getAbsolutePath();
File filePath = new File(path);
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdirs();
}
String fileName = file.getName();
fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())
+ "." + FORMAT.toLowerCase();
System.out.println("destPath:"+destPath);
ImageIO.write(image, FORMAT, new File(destPath));
return fileName;
}
//生成二维码图片,直接输出到OutputStream
/**
*
* @param content 二维码内容
* @param logoPath LOGO 路径
* @param output 输出路径
* @throws Exception
*/
public static void encode(String content, String logoPath, OutputStream output)
throws Exception {
BufferedImage image = QrCodeUtil.createImage(content, logoPath);
ImageIO.write(image, FORMAT, output);
}
//解析二维码图片,得到包含的内容
public static String decode(String path) throws Exception {
File file = new File(path);
BufferedImage image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, UNICODE);
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
}
3.编写一个controller,直接贴上代码,为了应用程序打包以后,可以在windows和liunx上运行,建立将logo图片,以静态资源形式,存放,方便程序可移槙性。
package com.myapp.controller;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.myapp.util.QrCodeUtil;
@RequestMapping("/barcode")
@Controller
public class QrCodeController {
// 生成带logo的二维码到response
@RequestMapping("/qrcode")
public void qrcode(HttpServletRequest request, HttpServletResponse response) {
String requestUrl = "http://www.baidu.com";
try {
//logo文件路径,如果没有把path设定为空值
String path = ClassUtils.getDefaultClassLoader().getResource("static/logo.jpeg").getPath();
OutputStream os = response.getOutputStream();
QrCodeUtil.encode(requestUrl, path, os);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成不带logo的二维码到response
@RequestMapping("/qrnologo")
public void qrnologo(HttpServletRequest request, HttpServletResponse response) {
String requestUrl = "http://www.baidu.com";
try {
OutputStream os = response.getOutputStream();
QrCodeUtil.encode(requestUrl, null, os);
} catch (Exception e) {
e.printStackTrace();
}
}
// 把二维码保存成文件
@RequestMapping("/qrsave")
@ResponseBody
public String qrsave() {
String requestUrl = "http://www.baidu.com";
try {
QrCodeUtil.save(requestUrl, null, "/data/qrcode2.jpg");
return "文件已保存";
} catch (Exception e) {
e.printStackTrace();
return "文件保存失败" + e.getMessage();
}
}
// 解析二维码中的文字
@RequestMapping("/qrtext")
@ResponseBody
public String qrtext() {
String url = "";
try {
url = QrCodeUtil.decode("/data/qrcode2.jpg");
} catch (Exception e) {
e.printStackTrace();
}
return "解析到的url:" + url;
}
}
3.1 logo图片存放路径如下
4. 在前端页面调用,代码如下,请注意API访问的路径和函数地址
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户管理</title>
<link rel="stylesheet" type="text/css"
href="../static/jquery-easyui-1.3.3/themes/default/easyui.css"></link>
<link rel="stylesheet" type="text/css"
href="../static/jquery-easyui-1.3.3/themes/icon.css"></link>
<script type="text/javascript"
src="../static/jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript"
src="../static/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript"
src="../static/jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
</head>
<body style="margin: 1px">
<img id="verification" src="../barcode/qrcode" style="cursor: pointer;" title="看不清?换一张" />
</body>
</html>
5.启动应用程序,在浏览器中访问就行了呢
以上是关于spring boot使用zxing 二维码应用的主要内容,如果未能解决你的问题,请参考以下文章