springboot里 用zxing 生成二维码

news/2024/11/20 0:42:59/

引入pom

		<!--二维码依赖--><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.3</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.3.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.28</version><scope>provided</scope></dependency>

核心方法

    private static final int QRCODE_SIZE = 320; // 二维码尺寸,宽度和高度均是320private static final String FORMAT_TYPE = "PNG"; // 二维码图片类型/*** 获取二维码图片** @param dataStr    二维码内容* @param needLogo   是否需要添加logo* @param bottomText 底部文字       为空则不显示* @return*/@SneakyThrowspublic static BufferedImage getQRCodeImage(String dataStr, boolean needLogo, String bottomText) {if (dataStr == null) {throw new RuntimeException("未包含任何信息");}HashMap<EncodeHintType, Object> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    //定义内容字符集的编码hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);        //定义纠错等级hints.put(EncodeHintType.MARGIN, 1);QRCodeWriter qrCodeWriter = new QRCodeWriter();BitMatrix bitMatrix = qrCodeWriter.encode(dataStr, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();int tempHeight = height;if (StringUtils.hasText(bottomText)) {tempHeight = tempHeight + 12;}BufferedImage image = new BufferedImage(width, tempHeight, 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);}}// 判断是否添加logoif (needLogo) {insertLogoImage(image);}// 判断是否添加底部文字if (StringUtils.hasText(bottomText)) {addFontImage(image, bottomText);}return image;}/*** 插入logo图片** @param source 二维码图片* @throws Exception*/private static void insertLogoImage(BufferedImage source) throws Exception {// 默认logo放于resource/static/目录下ClassPathResource classPathResource = new ClassPathResource("static/xbk.jpg");InputStream inputStream = classPathResource.getInputStream();if (inputStream == null || inputStream.available() == 0) {return;}Image src = ImageIO.read(inputStream);int width = 30;int height = 30;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;// 插入LOGOGraphics2D 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();}private static void addFontImage(BufferedImage source, String declareText) {//生成imageint defineWidth = QRCODE_SIZE;int defineHeight = 20;BufferedImage textImage = new BufferedImage(defineWidth, defineHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g2 = (Graphics2D) textImage.getGraphics();//开启文字抗锯齿g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);g2.setBackground(Color.WHITE);g2.clearRect(0, 0, defineWidth, defineHeight);g2.setPaint(Color.BLACK);FontRenderContext context = g2.getFontRenderContext();//部署linux需要注意 linux无此字体会显示方块,传入null选择默认字体Font font = new Font(null, Font.BOLD, 15);g2.setFont(font);LineMetrics lineMetrics = font.getLineMetrics(declareText, context);FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);float offset = (defineWidth - fontMetrics.stringWidth(declareText)) / 2;float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;g2.drawString(declareText, (int) offset, (int) y);Graphics2D graph = source.createGraphics();//开启文字抗锯齿graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//添加imageint width = textImage.getWidth(null);int height = textImage.getHeight(null);Image src = textImage;graph.drawImage(src, 0, QRCODE_SIZE - 8, width, height, Color.WHITE, null);graph.dispose();}

其中logo图片存放的路径为:resource/static/
在这里插入图片描述

调用

import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;@Controller
@RequestMapping("/qrcode")
public class QrCodeController {//1、生成带logo和底部文字得二维码@SneakyThrows@GetMapping("/getQrCode1")public void getQrCode1(HttpServletResponse response) {String content="test";String bottomTxt="01";ServletOutputStream os = response.getOutputStream();BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,true,bottomTxt);response.setContentType("image/png");ImageIO.write(bufferedImage,"png",os);}//2、生成不带logo和带底部文字的二维码@SneakyThrows@GetMapping("/getQrCode2")public void getQrCode2(HttpServletResponse response) {String content="test";ServletOutputStream os = response.getOutputStream();BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,false,null);response.setContentType("image/png");ImageIO.write(bufferedImage,"png",os);}//3、生成默认带logo不带底部文字得二维码@SneakyThrows@GetMapping("/getQrCode3")public void getQrCode3(HttpServletResponse response) {String content="test";ServletOutputStream os = response.getOutputStream();BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,true,null);response.setContentType("image/png");ImageIO.write(bufferedImage,"png",os);}//3、生成不带logo带底部文字得二维码@SneakyThrows@GetMapping("/getQrCode4")public void getQrCode4(HttpServletResponse response) {String content="test";String bottomTxt="01";ServletOutputStream os = response.getOutputStream();BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,false,bottomTxt);response.setContentType("image/png");ImageIO.write(bufferedImage,"png",os);}//5、生成不带logo带底部文字的二维码,返回base64@SneakyThrows@GetMapping("/getQrCode5")@ResponseBodypublic Object getQrCode5() {String content="test";String bottomTxt="01";BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,false,bottomTxt);ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流ImageIO.write(bufferedImage, "png", baos);//写入流中byte[] bytes = baos.toByteArray();//转换成字节BASE64Encoder encoder = new BASE64Encoder();String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\nString generateQrCode="data:image/jpg;base64," + png_base64;Map<String,String> map = new HashMap<>();map.put("generateQrCode",generateQrCode);return map;}}

http://www.ppmy.cn/news/1039169.html

相关文章

centos7安装 postgresql postgis pgrouting

centos7 源码编译太烦了。直接yum install ...... 一、版本信息&#xff1a; CentOS版本&#xff1a;CentOS Linux release 7.9.2009 (Core) PostgreSQL版本&#xff1a; PostgreSQL 12.0 PostGIS版本&#xff1a;postgis31 二、PostgresSQL PostGIS 安装 1、官网安装链接&…

力扣75——回溯

总结leetcode75中的回溯算法题解题思路。 上一篇&#xff1a;力扣75——二分查找 力扣75——回溯 1 电话号码的字母组合2 组合总和 III1-2解题总结 1 电话号码的字母组合 题目&#xff1a; 给定一个仅包含数字 2-9 的字符串&#xff0c;返回所有它能表示的字母组合。答案可以…

原生实现koa框架连接mongoose数据库

1.首先新建一个初始化文件 npm init -y2.下载koa框架所依赖的插件 npm i koa koa-bodyparser koa-router mongoose3.新建一个server.js文件作为我们的服务器 const Koa require(koa) const Router require(koa-router) //可以接受post请求 const bodyParser require(koa-b…

Redis持久化——AOF

介绍 Redis是运行在内存中的数据库&#xff0c;当我们关闭了Redis服务器后&#xff0c;内存中的数据会丢失吗&#xff1f; 答案是不会的&#xff0c;因为Redis有持久化功能&#xff0c;能够将内存中的数据保存到磁盘中的文件&#xff0c;以此来实现数据的永久保存。 在Redis中…

笔记:移植xenomai到nuc972(1)

xenomai是一个实时操作系统,想要使用它,先要移植I-pipe补丁 补丁在xenomai / ipipe-arm GitLab 我的内核是4.4-248的,合并上去会有几个小错误,随便改改就好 编译内核没有报错之后,接下来需要修改arch/arm/mach-nuc970/time.c 修改方法参考补丁里面其它设备的定时器驱动,就…

面向对象编程(OOP):Python中的抽象与封装

文章目录 &#x1f340;引言&#x1f340; 类与对象&#x1f340;封装&#x1f340;继承&#x1f340;多态&#x1f340;面向对象编程的优势&#x1f340;使用面向对象编程的场景&#x1f340;实例化与构造函数&#x1f340; 成员属性和类属性&#x1f340;魔术方法&#x1f34…

数据结构—排序

8.排序 8.1排序的概念 什么是排序&#xff1f; 排序&#xff1a;将一组杂乱无章的数据按一定规律顺序排列起来。即&#xff0c;将无序序列排成一个有序序列&#xff08;由小到大或由大到小&#xff09;的运算。 如果参加排序的数据结点包含多个数据域&#xff0c;那么排序往…

联想拯救者笔记本Win11系统键盘无法打字解决参考方法

一位好机友新购买的联想拯救者笔记本在使用过程中突然发现整个键盘都不能使用了、不能打字、按任何按键都没有反应&#xff0c;只有鼠标能正常操作&#xff1b;那么这是什么问题呢&#xff1f;能不能是笔记本的键盘坏了呢&#xff1f;还是笔记本出现了什么故障而引起键盘失灵呢…