1.引进依赖
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier><!-- jdk版本 -->
</dependency>
<!--二维码生成-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
2.二维码工具类
package com.ruoyi.web.controller.erweima;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Encoder;
/**
* 二维码工具类
*
* @author gu
*/
public class QrCodeUtils {
/**
* 红色
*/
private static final int BLACK = 0XFF1F00;
/**
* 白色
*/
private static final int WHITE = 0xFFFFFFFF;
/**
* 宽
*/
private static final int WIDTH = 350;
/**
* 高
*/
private static final int HEIGHT = 350;
/**
*
* 图片高度增加60
*
*/
private static final int PIC_HEIGHT=HEIGHT;
/**
* 二维码传图片
*
* @param matrix
* @return
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, PIC_HEIGHT, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < PIC_HEIGHT; y++) {
image.setRGB(x, y,WHITE);
}
}
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
/**
* 生成二维码
*
* @param content
* 扫描二维码的内容
* @param format
* 图片格式 jpg
* 文件
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static BufferedImage generateQrCode(String content, String format) throws Exception {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
@SuppressWarnings("rawtypes")
Map hints = new HashMap();
// 设置UTF-8, 防止中文乱码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 设置二维码四周白色区域的大小
hints.put(EncodeHintType.MARGIN, 1);
// 设置二维码的容错性
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 画二维码
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
BufferedImage image = toBufferedImage(bitMatrix);
return image;
}
/**
* 把生成的图片写到本地磁盘
*
* @param qrcFile 路径
* @param qrCodeContent 二维码内容
* @throws Exception
* @return
*/
/* public static BufferedImage generateQrCode(File qrcFile, String qrCodeContent, String pressText, String upText) throws Exception {
BufferedImage image=generateQrCode(qrCodeContent, "jpg");
Graphics g = image.getGraphics();
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
//设置字体
Font font=new Font("宋体", Font.PLAIN, 26);
g.setFont(font);
g.setColor(Color.black);
FontMetrics metrics = g.getFontMetrics(font);
// 文字在图片中的坐标 这里设置在中间
int startX = (WIDTH - metrics.stringWidth(pressText)) / 2;
int startY=HEIGHT+(PIC_HEIGHT-HEIGHT)/2-10;
int upstartX=(WIDTH - metrics.stringWidth(upText)) / 2;
int upstartY=(PIC_HEIGHT-HEIGHT)/2-20;
g.drawString(pressText, startX, startY);
g.drawString(upText, upstartX, upstartY);
g.dispose();
image.flush();
try {
ImageIO.write(image, "jpg",qrcFile);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
*/
public static BufferedImage generateQrCode(File qrcFile, String qrCodeContent) throws Exception {
BufferedImage image=generateQrCode(qrCodeContent, "jpg");
Graphics g = image.getGraphics();
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
//设置字体
Font font=new Font("微软雅黑", Font.PLAIN, 26);
g.setFont(font);
g.setColor(Color.black);
FontMetrics metrics = g.getFontMetrics(font);
// 文字在图片中的坐标 这里设置在中间
int startY=HEIGHT+(PIC_HEIGHT-HEIGHT)/2-10;
int upstartY=(PIC_HEIGHT-HEIGHT)/2-20;
image.flush();
try {
ImageIO.write(image, "jpg",qrcFile);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
/**
*
* 生成二维码并使用Base64编码
*
*
* @param content 二维码内容
*
* @return 返回base64图片
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static String getBase64QRCode(String content) throws Exception {
String format = "png";
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
@SuppressWarnings("rawtypes")
Map hints = new HashMap();
// 设置二维码四周白色区域的大小
hints.put(EncodeHintType.MARGIN, 1);
// 设置二维码的容错性
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 画二维码
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。
ImageIO.write(image, format, os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。
byte b[] = os.toByteArray();//从流中获取数据数组。
String base64String = new BASE64Encoder().encode(b);
// Base64编码
return base64String;
}
/**
* test
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
QrCodeUtils utils=new QrCodeUtils();
String content="Bicycle/"+"021545"+"/webapp/transportationManagementOffice";;
String pressText="021545";
String fileName="E://12345.png";
File qrcFile = new File(fileName);
generateQrCode(qrcFile, content);
utils.erweima( qrcFile, content, pressText, fileName);
}
//资源的调取
public void erweima(File qrcFile, String content, String pressText, String fileNameUpload) throws Exception {
BufferedImage qrCodeImage =QrCodeUtils.generateQrCode(qrcFile, content);
//获取本地资源
// String path = ClassUtils.getDefaultClassLoader().getResource("QRCode.png").getPath();
File file1 = ResourceUtils.getFile("classpath:static/QRCode.png");
// ClassPathResource classPathResource = new ClassPathResource("QRCode.png");
String basepath= URLDecoder.decode(file1.getPath(),"utf-8");//这样就能解决掉那个空格的问题了。
QRcodeTest.createPicture(qrCodeImage, basepath, pressText, fileNameUpload);
}
}
3.生成中间带logo的二维码
package com.ruoyi.web.controller.erweima;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class QRcodeTest {
public static void main(String[] args) throws Exception {
File qrcFile = new File("e:/1.jpg");
String qrCodeContent="dfdfdfd";
String pressText="编号:HL01000";
String UpText="55";
BufferedImage qrCodeImage =QrCodeUtils.generateQrCode(qrcFile, qrCodeContent);
createPicture(qrCodeImage, "E:\\QRCode.png", pressText, "E:/32.png");
}
/**
* 生成中间带logo的二维码
*
* @param content 二维码内容
* @param logoPath logo图标的地址
* @return
*/
public static BufferedImage generateQrCode(String content, String logoPath) {
BufferedImage image = QrCodeUtil.generate(
content, // 二维码内容
QrConfig.create().setImg(logoPath)// 附带logo
.setWidth(500) // 二维码的宽
.setHeight(500) // 二维码的高
.setMargin(0)); // 边距
return image;
}
/**
* 带文字和背景图片的二维码创建
*
* @param image 生成的二维码
* @param bgPath 背景图片的路径
* @param text 二维码上的文字
* @param savePath 生成图片的保存位置
* @throws IOException
*/
public static void createPicture(BufferedImage image, String bgPath, String text, String savePath) {
try {
// 首先先画背景图片
BufferedImage backgroundImage = ImageIO.read(new File(bgPath));
// 背景图片的宽度
int bgWidth = backgroundImage.getWidth();
// 二维码的宽度
int qrWidth = image.getWidth();
// 二维码距离背景图片横坐标(X)的距离,居中显示
int distanceX = (bgWidth - qrWidth) / 2;
// 二维码距离背景图片纵坐标(Y)的距离
int distanceY = distanceX;
// 基于图片backgroundImage对象打开绘图
Graphics2D rng = backgroundImage.createGraphics();
rng.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
rng.drawImage(image, distanceX, distanceY, null);
//设置字体
Font font = new Font("微软雅黑", Font.BOLD , 26);
rng.setFont(font);
rng.setColor(Color.black);
// 获取当前文字的对象
FontMetrics metrics = rng.getFontMetrics(font);
// 文字在图片中的坐标 这里设置在中间
int startX = (bgWidth - metrics.stringWidth(text)) / 2; //当前文字对象到横坐标(X)的距离
int startY = backgroundImage.getHeight() - 28; //当前文字对象到纵坐标(Y)的距离
rng.drawString(text, startX, startY);
// 处理绘图
rng.dispose();
image = backgroundImage;
image.flush();
// 将绘制好的图片写入当前路径中
ImageIO.write(image, "png", new File(savePath));
} catch (IOException e) {
e.printStackTrace();
}
}
}