前言
通过java生成二维码,使用手机扫一扫即可获取相关内容。
一、基本准备
- IDE:IDEA 2022.1.3
- JDK:1.8
- 依赖管理工具:Maven
- OS:Win10
二、生成二维码(项目创建过程跳过,创建一个普通的maven工程即可)
1. 引入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
2. 创建类和方法
- 如果只是为了实现功能,直接复制以下内容即可。
public class GenerateQR {
/**
* 生成二维码的方法
* @param content 二维码内容
* @param path 二维码图片保存路径
*/
public static void code(String content,String path){
//设置二维码宽
int width = 400;
//设置二维码高
int height = 400;
//设置二维码的后缀名称
String format = "png";
//设置map集合要往二维码内添加的参数
@SuppressWarnings("rawtypes")
Map map = new HashMap();
//设置二维码的级别
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//设置二维码中文本的编码格式
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
//设置二维码的外边框
map.put(EncodeHintType.MARGIN, 5);
try {
//创建生成二维码对象,调用方法将所需要的参数放入
BitMatrix bm = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,map);
//创建path对象将物理地址放到file文件内,然后生成path对象
Path paths = new File(path).toPath();
//使用writeToPath方法调用下载,里面的参数是下载的对象照片,下载的后缀名称,下载的物理路径地址
MatrixToImageWriter.writeToPath(bm, format, paths);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3. 测试
public static void main(String[] args) throws Exception {
code("这是一段测试内容" +
"\n"
+
"时间:"+new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date())
,"C:\\Users\\29517\\Desktop\\test.png");
}
使用手机扫码。
三、给二维码下空白处添加说明文字
1. 代码
/**
*
* @param pressText 文字
* @param qrFile 二维码图片文件路径
* @param color 颜色
* @param fontSize 字体大小
* @throws Exception
*/
public static void pressText(String pressText, File qrFile ,Color color, int fontSize) throws Exception {
//如果有中文,建议使用gbk;否则容易出现在ide中运行好用,将程序打包后无法正常写入中文。
pressText = new String(pressText.getBytes("gbk"),"gbk");
Image src = ImageIO.read(qrFile);
int imageW = src.getWidth(null);
int imageH = src.getHeight(null);
BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, imageW, imageH, null);
//设置画笔的颜色
g.setColor(color);
//设置字体
Font font = new Font("宋体", Font.BOLD, fontSize);
FontMetrics metrics = g.getFontMetrics(font);
int startX = 80;
int startY = 380;
g.setFont(font);
g.drawString(pressText, startX, startY);
g.dispose();
FileOutputStream out = new FileOutputStream(qrFile);
ImageIO.write(image, "JPEG", out);
out.close();
System.out.println("二维码添加文本成功");
}
2. 测试
pressText("这是二维码下方的一段文字",new File("C:\\Users\\29517\\Desktop\\test.png"),
Color.BLACK,20);
至此,通过java生成二维码的功能实现完成,希望可以帮到你。