版权声明:本文为博主原创文章,转载记得声明出处。 https://blog.csdn.net/qq_40100817/article/details/82797133
生成二维码的方法大体分为两种:1. 展示时候引用Qrcode.js;2.后台生成二维码保存成图片,前端显示
1.QRCode.js 是一个用于生成二维码的 JavaScript 库。主要是通过获取 DOM 的标签,再通过 HTML5 Canvas 绘制而成
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">
<head>
<title>Javascript 二维码生成库:QRCode</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://static.runoob.com/assets/qrcode/qrcode.min.js"></script>
</head>
<body>
<input id="text" type="text" value="http://www.runoob.com" style="width:80%" /><br />
<div id="qrcode" style="width:100px; height:100px; margin-top:15px;"></div>
<script type="text/javascript">
var qrcode = new QRCode(document.getElementById("qrcode"), {
width : 100,
height : 100
});
function makeCode () {
var elText = document.getElementById("text");
if (!elText.value) {
alert("Input a text");
elText.focus();
return;
}
qrcode.makeCode(elText.value);
}
makeCode();
$("#text").
on("blur", function () {
makeCode();
}).
on("keydown", function (e) {
if (e.keyCode == 13) {
makeCode();
}
});
</script>
</body>
</html>
![](https://i-blog.csdnimg.cn/blog_migrate/afd800773ec31a247abc49bda094dee2.png)
2.后台生成二维码
必不可少的maven依赖
<!-- 条形码、二维码生成 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
package com.thinkgem.jeesite.common.qrcode;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* 二维码 添加 logo图标 处理的方法,
* 模仿微信自动生成二维码效果,有圆角边框,logo和二维码间有空白区,logo带有灰色边框
* @author: huxm
* @date: 2018年8月29日 下午12:10:35
* @version: v1.0.0
*
*/
public class LogoConfig {
/**
* 设置 logo
* @param matrixImage 源二维码图片
* @return 返回带有logo的二维码图片
* @throws IOException
* @author Administrator sangwenhao
*/
public BufferedImage LogoMatrix(BufferedImage matrixImage) throws IOException{
/**
* 读取二维码图片,并构建绘图对象
*/
Graphics2D g2 = matrixImage.createGraphics();
int matrixWidth = matrixImage.getWidth();
int matrixHeigh = matrixImage.getHeight();
/**
* 读取Logo图片
*/
BufferedImage logo = ImageIO.read(new File(""));
//开始绘制图片
g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//绘制
BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
g2.setStroke(stroke);// 设置笔画对象
//指定弧度的圆角矩形
RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
g2.setColor(Color.white);
g2.draw(round);// 绘制圆弧矩形
//设置logo 有一道灰色边框
BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
g2.setStroke(stroke2);// 设置笔画对象
RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
g2.setColor(new Color(128,128,128));
g2.draw(round2);// 绘制圆弧矩形
g2.dispose();
matrixImage.flush() ;
return matrixImage ;
}
}
/**
* @Package: com.thinkgem.jeesite.common.qrcode
* @author: huxm
* @date: 2018年8月29日 下午12:10:35
*/
package com.thinkgem.jeesite.common.qrcode;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类直接拷贝到源码中使用,当然你也可以自己写个
* 生产条形码的基类
*/
public class MatrixToImageWriter {
private static final int BLACK = 0xFF000000;//用于设置图案的颜色
private static final int WHITE = 0xFFFFFFFF; //用于背景色
private MatrixToImageWriter() {
}
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.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, (matrix.get(x, y) ? BLACK : WHITE));
// image.setRGB(x, y, (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
}
}
return image;
}
public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
BufferedImage image = toBufferedImage(matrix);
//设置logo图标
/*LogoConfig logoConfig = new LogoConfig();
image = logoConfig.LogoMatrix(image);*/
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}else{
System.out.println("图片生成成功!");
}
}
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
BufferedImage image = toBufferedImage(matrix);
//设置logo图标
/*LogoConfig logoConfig = new LogoConfig();
image = logoConfig.LogoMatrix(image);*/
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
public static void Encode_QR_CODE(String contents,String format,String path,int width,int height,int encodeHintType) throws IOException, WriterException{
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 内容所使用字符集编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值
// hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值
hints.put(EncodeHintType.MARGIN, encodeHintType);//设置二维码边的空度,非负数
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,//要编码的内容
//编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
//Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
//MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
BarcodeFormat.QR_CODE,
width, //条形码的宽度
height, //条形码的高度
hints);//生成条形码时的一些配置,此项可选
// 生成二维码
File outputFile = new File(path);//指定输出路径
MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
}
}
/**
* @Package: com.thinkgem.jeesite.common.qrcode
* @author: huxm
* @date: 2018年8月29日 下午12:10:35
*/
package com.thinkgem.jeesite.common.qrcode;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.thoughtworks.xstream.io.path.Path;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
/**
* @Description: 生成二维码的工具类
*
* @author: huxm
* @date: 2018年8月29日 下午12:10:35
* @version: v1.0.0
*/
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 100;
// LOGO宽度
private static final int WIDTH = 30;
// LOGO高度
private static final int HEIGHT = 30;
/**
* 生成二维码
* @param content 源内容
* @param imgPath 生成二维码保存的路径
* @param needCompress 是否要压缩
* @return 返回二维码图片
* @throws Exception
*/
private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
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 (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 在生成的二维码中插入图片
* @param source
* @param imgPath
* @param needCompress
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
File file = new File(imgPath);
//System.out.println(file+"****************************");
if (!file.exists()) {
System.err.println("" + imgPath + " 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = 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_SIZE - width) / 2;
int y = (QRCODE_SIZE - 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二维码,并保存到磁盘
* @param content 链接或者内容
* @param imgPath logo图片
* @param destPath 保存二维码图片的文件路径
* @param needCompress
* @throws Exception
*/
public static Boolean encode(String content, String imgPath, String destPath, boolean needCompress,String random) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
if(image==null){
return false;
}
mkdirs(destPath);
String file = random + ".jpg";//生成随机文件名
ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
return true;
}
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir。(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}
public static void encode(String content, OutputStream output) throws Exception {
QRCodeUtil.encode(content, null, output, false);
}
/**
* 从二维码中,解析数据
* @param file 二维码图片文件
* @return 返回从二维码中解析到的数据值
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}
@SuppressWarnings({"rawtypes", "unchecked"})
private static void createZxing() throws WriterException, IOException {
int width=300;
int hight=300;
String format="png";
String content="www.baidu.com";
HashMap hints=new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//纠错等级L,M,Q,H
hints.put(EncodeHintType.MARGIN, 2); //边距
BitMatrix bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, hight, hints);
Path file=(Path) new File("D:/download/imag.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, (java.nio.file.Path) file);
}
private static void readZxing() throws IOException, NotFoundException {
MultiFormatReader read = new MultiFormatReader();
File file=new File("D:/download/imag.png");
BufferedImage image=ImageIO.read(file);
Binarizer binarizer=new HybridBinarizer(new BufferedImageLuminanceSource(image));
BinaryBitmap binaryBitmap=new BinaryBitmap(binarizer);
Result res=read.decode(binaryBitmap);
System.out.println(res.toString());
System.out.println(res.getBarcodeFormat());
System.out.println(res.getText());
}
}
//根据内容生成二维码
String imgPath = "/static/images/qrcode/";//生成的路径
String path = request.getSession().getServletContext().getRealPath(imgPath);//路径整合
String code = "xxxxx";//生成的内容(可以是文本数字或者网址)
String imgName= code+".jpg";//生成二维码图片的名称
String pathName = path+imgName;//生成的路径名(保存到数据库的)
FileUtils.deleteFile(pathName);//调用文件操作工具类删除这个图片(如果存在)
//调用工具类生成图片(code:生成的内容;"jpg":生成的二维码图片格式;pathName:图片生成的路径;80:宽,高;1:二维码周围白边的大小,如果不需要设为0,最大为5)
MatrixToImageWriter.Encode_QR_CODE(code, "jpg", pathName,80,80,1);
//如果需要生成带logo的把工具类中注释的LogoConfig去除,然后图片给到
3.后台生成二维码,Zxing生成带logo和文字的二维码
/**
* @Package: com.thinkgem.jeesite.common.qrcode
* @author: huxm
* @date: 2018年10月25日 下午3:29:59
*/
package com.thinkgem.jeesite.common.qrcode;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码工具类
*
* @ClassName: BarcodeUtils.java
* @version: v1.0.0
* @author: pll
* @date: 2018年6月4日 下午2:51:54
*/
public class BarcodeUtils {
private static final int QRCOLOR = 0xFF000000; // 二维码颜色 默认是黑色
private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色
private static final int WIDTH = 215; // 二维码宽
private static final int HEIGHT = 215; // 二维码高
private static final int WORDHEIGHT = 235; // 加文字二维码高
/**
* 用于设置QR二维码参数
*/
private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
private static final long serialVersionUID = 1L;
{
// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 设置编码方式
put(EncodeHintType.CHARACTER_SET, "utf-8");
put(EncodeHintType.MARGIN, 0);
}
};
/**
* 设置 Graphics2D 属性 (抗锯齿)
* @param graphics2D
*/
private static void setGraphics2D(Graphics2D graphics2D){
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
graphics2D.setStroke(s);
}
/**
* 生成二维码图片存储到filePath中
*
* @param content
* 二维码内容
* @param filePath
* 成二维码图片保存路径
* @return
*/
public static boolean createImg(String content, String filePath) {
boolean flag = false;
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
// 图片输出路径
String code = content.split("=")[1]; // 设备编号
File file = new File(filePath + "//PSD" + code + ".jpg");
if (!file.exists()) {
// 如果文件夹不存在则创建
file.mkdirs();
}
// 输出二维码图片到文件夹
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file);
flag = true;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 把带logo的二维码下面加上文字
* @param image
* @param words
* @return
*/
private static BufferedImage insertWords(BufferedImage image,String words){
// 新的图片,把带logo的二维码下面加上文字
if (StringUtils.isNotEmpty(words)) {
//创建一个带透明色的BufferedImage对象
BufferedImage outImage = new BufferedImage(WIDTH, WORDHEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D outg = outImage.createGraphics();
setGraphics2D(outg);
// 画二维码到新的面板
outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
// 画文字到新的面板
Color color=new Color(0,0,0);
outg.setColor(color);
// 字体、字型、字号
outg.setFont(new Font("微软雅黑", Font.PLAIN, 20));
//文字长度
int strWidth = outg.getFontMetrics().stringWidth(words);
//总长度减去文字长度的一半 (居中显示)
int wordStartX=(WIDTH - strWidth) / 2;
//height + (outImage.getHeight() - height) / 2 + 12
int wordStartY=HEIGHT+18;
// 画文字
outg.drawString(words, wordStartX, wordStartY);
outg.dispose();
outImage.flush();
return outImage;
}
return null;
}
/**
* @description 生成带logo的二维码图片 二维码下面带文字
* @param logoFile loge图片的路径
* @param bgFile 背景图片的路径
* @param codeFile 图片输出路径
* @param qrUrl 二维码内容
* @param words 二维码下面的文字
*/
public static void drawLogoQRCode(File codeFile, String qrUrl, String words) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
}
}
// 新的图片,把带logo的二维码下面加上文字
image=insertWords(image,words);
image.flush();
ImageIO.write(image, "png", codeFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
/* //logo
File logoFile = new File("G://picture/03.png");
//背景图片
File bgFile = new File("G://picture/01.png");*/
//生成图片
File qrCodeFile = new File("E:\\\\youdao\\\\1234.jpg");
//二维码内容
String url = "https://w.url.cn/s/AYmfAV3";
//二维码下面的文字
String words = "1234";
drawLogoQRCode(qrCodeFile, url, words);
}
}