如何使用 Java 生成二维码?
作者:许你一世流离
来源:blog.csdn.net/weixin_39936341/article/details/82910051
1. 下载jar包(QRCode.jar)
下载网址如下。
QRCode生成二维码网址:http://swetake.com/qrcode/index-e.html
2. maven项目手动引入jar包
mvn install:install-file
-DgroupId=包名
-DartifactId=项目名
-Dversion=版本号
-Dpackaging=jar-Dfile=jar文件所在路径
1,本地D盘中有个jar,例如:D:workRepositoryQRCode.jar
2,cmd 中执行mvn install
命令格式为:mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
例如:install-file -Dfile=D:workRepositoryQRCode.jar -DgroupId=QRCode -DartifactId=QRCode -Dversion=3.0 -Dpackaging=jar -DgeneratePom=true -DcreateChecksum=true
(注意空格)
3,在pom.xml中增加如下语句
<dependency>
<groupId>QRCode</groupId>
<artifactId>QRCode</artifactId>
<version>3.0</version>
</dependency>
手动引入成功如下:BUILD SUCCESS
C:Userszhm>mvn install:install-file -Dfile=D:workRepositoryQRCode.jar -DgroupId=QRCode -DartifactId=QRCode -Dversion=3.0 -Dpackaging=jar -DgeneratePom=true -DcreateChecksum=true
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-install-plugin:2.4:install-file (default-cli) @ standalone-pom ---
[INFO] Installing D:workRepositoryQRCode.jar to D:workRepositoryQRCodeQRCode3.0QRCode-3.0.jar
[INFO] Installing C:UserszhmAppDataLocalTempmvninstall6966241826790879082.pom to D:workRepositoryQRCodeQRCode3.0QRCode-3.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.604 s
[INFO] Finished at: 2018-09-30T15:16:23+08:00
[INFO] Final Memory: 7M/123M
[INFO] ------------------------------------------------------------------------
或者不做以上操作引入jar包,pom文件直接指向QRCode.jar在本地路径
<dependency>
<groupId>QRCode</groupId>
<artifactId>QRCode</artifactId>
<version>3.0</version>
<scope>system</scope>
<systemPath>D:/work/Repository/QRCode.jar</systemPath>
</dependency>
3. 编写实体类实现二维码的生成
package com.st.project.common;
import com.swetake.util.Qrcode;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* 二维码工具类
*/
public class CreateQRCode {
/**
* 创建二维码
* @param qrData 生成二维码中要存储的信息
* @param path 二维码图片存储路径 eg:"D:/qrcode.png"
* @throws Exception
*/
public static boolean creatQrcode(String qrData, String path) {
try {
Qrcode qrcode = new Qrcode();
qrcode.setQrcodeErrorCorrect("M");//纠错等级(分为L、M、H三个等级)
qrcode.setQrcodeEncodeMode("B");//N代表数字,A代表a-Z,B代表其它字符
qrcode.setQrcodeVersion(7);//版本
//设置一下二维码的像素
int width = 67 + 12 * (7 - 1);
int height = 67 + 12 * (7 - 1);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//绘图
Graphics2D gs = bufferedImage.createGraphics();
gs.setBackground(Color.WHITE);
gs.setColor(Color.BLACK);
gs.clearRect(0, 0, width, height);//清除下画板内容
//设置下偏移量,如果不加偏移量,有时会导致出错。
int pixoff = 2;
byte[] d = qrData.getBytes("utf-8");
if (d.length > 0 && d.length < 120) {
boolean[][] s = qrcode.calQrcode(d);
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s.length; j++) {
if (s[j][i]) {
gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
}
}
}
}
gs.dispose();
bufferedImage.flush();
ImageIO.write(bufferedImage, "png", new File(path));
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 解析二维码(QRCode)
*
* @param imgPath 图片路径
* @return
*/
public static String decoderQRCode(String imgPath) {
//QRCode 二维码图片的文件
File imageFile = new File(imgPath);
BufferedImage bufImg = null;
String content = null;
try {
bufImg = ImageIO.read(imageFile);
QRCodeDecoder decoder = new QRCodeDecoder();
content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} catch (DecodingFailedException dfe) {
System.out.println("Error: " + dfe.getMessage());
dfe.printStackTrace();
}
return content;
}
}
/**
* 二维码基础类
*/
class TwoDimensionCodeImage implements QRCodeImage {
//BufferedImage作用将一幅图片加载到内存中
BufferedImage bufImg;
public TwoDimensionCodeImage(BufferedImage bufImg) {
this.bufImg = bufImg;
}
@Override
public int getWidth() {
return bufImg.getWidth();//返回像素宽度
}
@Override
public int getHeight() {
return bufImg.getHeight();//返回像素高度
}
@Override
public int getPixel(int i, int i1) {
return bufImg.getRGB(i, i1);//得到长宽值,即像素值,i,i1代表像素值
}
}
4. controller调用
package com.st.project.controller;
import com.st.project.common.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import static com.st.project.common.CreateQRCode.creatQrcode;
import static com.st.project.common.CreateQRCode.decoderQRCode;
/**
* 创建二维码
*/
@Controller
@RequestMapping("/qrcode")
public class QrcodeController {
@Value("${portals.upload.image.path}")
private String qrcodePath; //二维码存储路径
/**
* 创建二维码
* @return
*/
@ResponseBody
@PostMapping("/add.dd")
public AjaxResult addQrcode(HttpServletRequest request){
AjaxResult ajaxResult = new AjaxResult();
ajaxResult.setState(false);
String qrData=request.getParameter("qrData");
String qrSuffix=request.getParameter("qrSuffix");
String qrcode=System.currentTimeMillis()+"."+qrSuffix;
String path=qrcodePath+qrcode;
boolean getQrcode=creatQrcode(qrData,path);
if(getQrcode==true){
ajaxResult.setState(true);
ajaxResult.setData(qrcode);
}
return ajaxResult;
}
/**
* 解析二维码
* @return
*/
@ResponseBody
@PostMapping("/decoder.dd")
public AjaxResult decoderQrcode(HttpServletRequest request){
AjaxResult ajaxResult = new AjaxResult();
ajaxResult.setState(false);
String qrcode=request.getParameter("qrcode");
String qrData=decoderQRCode(qrcodePath+qrcode);
if(qrData!=null && !"".equals(qrData)){
ajaxResult.setState(true);
ajaxResult.setData(qrData);
}
return ajaxResult;
}
}
此时已生成一张名为qrcode.png的二维码图片:
近期热文推荐:
1.1,000+ 道 Java面试题及答案整理(2021最新版)
2.别在再满屏的 if/ else 了,试试策略模式,真香!!
3.卧槽!Java 中的 xx ≠ null 是什么新语法?
4.Spring Boot 2.5 重磅发布,黑暗模式太炸了!
5.《Java开发手册(嵩山版)》最新发布,速速下载!
觉得不错,别忘了随手点赞+转发哦!