1.依赖:

<!-- https://mvnrepository.com/artifact/com.google.zxing/core --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.4.1</version></dependency>

2.工具类:

第一个类:谷歌提供的帮助的类

package com.zyp.util.code;import com.google.zxing.LuminanceSource;import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;/*** @author leishen*/
public class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white}}}this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);this.image.getGraphics().drawImage(image, 0, 0, null);this.left = left;this.top = top;}@Overridepublic byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}image.getRaster().getDataElements(left, top + y, width, 1, row);return row;}@Overridepublic byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];image.getRaster().getDataElements(left, top, width, height, matrix);return matrix;}@Overridepublic boolean isCropSupported() {return true;}@Overridepublic LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);}@Overridepublic boolean isRotateSupported() {return true;}@Overridepublic LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);Graphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();int width = getWidth();return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);}}

第二个类:个人封装的工具类

package com.zyp.util.code;import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;public class QRCodeUtil {/*** 二维码颜色 默认是黑色*/private static final int QRCOLOR = 0xFF000000;/*** 背景颜色 白色*/private static final int BGWHITE = 0xFFFFFFFF;/*** 编码*/private static final String CHARSET = "utf-8";/***  二维码尺寸-宽度*/private static int QRCODE_WIDTH=300;/***  二维码尺寸-高度*/private static int QRCODE_HEIGHT=300;/*** 画布高度*/private static int CANVAS_HEIGHT=350;/*** 画布宽度*/private static  int CANVAS_WIDTH=300;/*** LOGO默认最大宽度*/private static  int LOGO_WIDTH = 90;/*** LOGO默认最大高度*/private static  int LOGO_HEIGHT = 90;/*** 设置logo大小* @param logoWidth LOGO默认最大宽度* @param logHeight LOGO默认最大高度* @return*/public static void setLogoSize(int logoWidth,int logHeight){QRCodeUtil.LOGO_WIDTH=logoWidth;QRCodeUtil.LOGO_HEIGHT=logHeight;}/*** 设置画布大小* @param canvasWidth 二维码尺寸-宽度* @param canvasHeight 二维码尺寸-高度* @return*/public static void setCanvasSize(int canvasWidth,int canvasHeight){QRCodeUtil.CANVAS_WIDTH=canvasWidth;QRCodeUtil.CANVAS_HEIGHT=canvasHeight;}/*** 设置二维码大小* @param qrcodeWidth 画布宽度* @param qrcodeHeight 画布高度* @return*/public static void setQrCodeSize(int qrcodeWidth,int qrcodeHeight){QRCodeUtil.QRCODE_WIDTH=qrcodeWidth;QRCodeUtil.QRCODE_HEIGHT=qrcodeHeight;}/*** 创建纯净的二维码* @param content 二维码内容* @return* @throws Exception*/public static BufferedImage createQRCode(String content) throws Exception {if (StringUtils.isBlank(content)) {throw new Exception("二维码内容不能为空");}//用于设置QR二维码参数Hashtable hints = new Hashtable();// 容错级别设置 默认为Lhints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 字符转码格式设置hints.put(EncodeHintType.CHARACTER_SET, CHARSET);// 空白边距设置hints.put(EncodeHintType.MARGIN, 0);MultiFormatWriter multiFormatWriter = new MultiFormatWriter();BitMatrix bm = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE,QRCODE_WIDTH, QRCODE_HEIGHT,hints);//创建一个图片缓冲区存放二维码图片BufferedImage image = new BufferedImage(QRCODE_WIDTH, QRCODE_HEIGHT, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < QRCODE_WIDTH; x++) {for (int y = 0; y < QRCODE_HEIGHT; y++) {image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);}}return image;}/*** 二维码里面插入logo** @param source       图片对象* @param logoPath      logo路径* @param needCompress true表示将嵌入二维码的图片进行压缩,false为则表示不压缩* @return* @throws Exception*/public static BufferedImage insertLogo(BufferedImage source, String logoPath, boolean needCompress) throws Exception {File file = new File(logoPath);if (!file.exists()) {throw new Exception("logo图片路径"+logoPath+"不存在");}//读取图片Image src = ImageIO.read(new File(logoPath));// 获取图像的宽度int width = src.getWidth(null);// 获取图像的宽度int height = src.getHeight(null);if (needCompress) {if (width > LOGO_WIDTH) {width = LOGO_WIDTH;}if (height > LOGO_HEIGHT) {height = LOGO_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;}//插入logoGraphics2D graph = source.createGraphics();int x = (QRCODE_WIDTH - width) / 2;int y = (QRCODE_HEIGHT - 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.dispose();graph.draw(shape);source.flush();return source;}/*** 文件解密* @param file 文件对象* @return* @throws Exception*/public static String decode(File file) throws Exception {if (!file.exists()) {throw new Exception("文件不存在");}BufferedImage image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Hashtable hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);Result result = new MultiFormatReader().decode(bitmap, hints);return result.getText();}/*** 在二维码下方添加文字 --建议最后添加下方文字* @param image 图片对象* @param font 字体格式 默认宋体 28号* @param color 字体颜色 默认白色* @param pressText 下方文字* @return* @throws Exception*/public static BufferedImage pressText(BufferedImage image,Font font,Color color,String pressText) throws Exception {if (StringUtils.isBlank(pressText)) {throw new Exception("文字不能为空");}pressText = new String(pressText.getBytes(), "utf-8");//TYPE_INT_RGB设置颜色BufferedImage finalImage = new BufferedImage(CANVAS_WIDTH, CANVAS_HEIGHT, BufferedImage.TYPE_INT_RGB);Graphics g = finalImage.createGraphics();// 在画布上画上二维码  X轴Y轴,宽度高度g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(),null);//设置画笔的颜色if (color==null) {g.setColor(Color.WHITE);}else{g.setColor(color);}if (font==null) {font = new Font("宋体",  Font.PLAIN, 28);}g.setFont(font);//drawString(文字信息、x轴、y轴)方法根据参数设置文字的坐标轴 ,根据需要来进行调整int startX =(QRCODE_WIDTH - g.getFontMetrics().stringWidth(pressText)) / 2;int startY =CANVAS_HEIGHT-(CANVAS_HEIGHT-QRCODE_HEIGHT)/2+font.getSize()/4;g.drawString(pressText, startX, startY);g.dispose();image=finalImage;image.flush();return image;}/*** 输出到本地* @param image 图片对象* @param formatName 格式 默认png* @param destPath 路径 默认桌面* @throws IOException*/public static void writeToLocalByPath(RenderedImage image,String formatName,String destPath) throws IOException {if (formatName==null) {formatName="png";}if (StringUtils.isBlank(destPath)) {//当前用户桌面路径File desktopDir = FileSystemView.getFileSystemView() .getHomeDirectory();long l = System.currentTimeMillis();destPath= desktopDir.getAbsolutePath()+"\\"+l+"."+formatName;}File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}ImageIO.write(image, formatName,file);};/*** 输出到本地* @param image 图片对象* @param formatName 格式 默认png* @param file 文件对象* @throws IOException*/public static void writeToLocalByFile(RenderedImage image,String formatName,File file) throws IOException {// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}if (formatName==null) {formatName="png";}ImageIO.write(image, formatName, file);};/*** 输出到客户端* @param image 图片对象* @param formatName 格式 默认png* @param response 响应* @throws IOException*/public static void writeToStream(RenderedImage image, String formatName, HttpServletResponse response) throws IOException {if (formatName==null) {formatName="png";}ImageIO.write(image, formatName, response.getOutputStream());}public static void main(String[] args) throws Exception {// 存放在二维码中的内容
//        String content = "https://qr.alipay.com/fkx17652i95teercapvji5d";
//        BufferedImage image = QRCodeUtil.createQRCode(content);
//        image=QRCodeUtil.pressText(image,null,Color.GREEN,"扫一扫向我付款");
//        String imgPath = "D:\\qrCode\\1.jpg";
//        image=QRCodeUtil.insertLogo(image,imgPath,true);
//        String destPath = "D:\\qrCode\\test.jpg";String destPath = "C:\\Users\\leishen\\Desktop\\20221123.jpeg";
//        QRCodeUtil.writeToLocalByPath(image, "jpg", null);String decode = QRCodeUtil.decode(new File(destPath));System.out.println("decode = " + decode);}
}

3.代码测试

3.1.控制层:

package com.zyp.controller;import com.zyp.model.dto.QRCodeDto;
import com.zyp.util.code.QRCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;@RestController
@RequestMapping("qRCode/")
@Api(tags = "二维码测试")
public class QRCodeController {/*** 由于有MultipartFile,此处不能使用@RequestBody* @param dto* @param response* @throws Exception*/@ApiOperation("生成二维码")@PostMapping(value = "generateQRCode")public void generateQRCode(@Validated QRCodeDto dto, HttpServletResponse response){// 存放在二维码中的内容String content = dto.getContent();BufferedImage image = null;File uploadFile = null;try {image = QRCodeUtil.createQRCode(content);uploadFile =getUploadFile(dto.getLogoFile());image=QRCodeUtil.pressText(image,null, Color.GREEN,dto.getPressText());image=QRCodeUtil.insertLogo(image,uploadFile.getPath(),true);QRCodeUtil.writeToStream(image, "jpg", response);} catch (Exception e) {throw new RuntimeException(e);}finally {if (uploadFile != null) {//删除临时文件uploadFile.delete();}}}@ApiOperation("二维码解析")@PostMapping("parseQRCode")public String parseQRCode(@RequestParam(value = "file") MultipartFile file)  {File uploadFile = null;try {uploadFile = getUploadFile(file);String decode = QRCodeUtil.decode(uploadFile);return decode;} catch (Exception e) {throw new RuntimeException(e);}finally {if (uploadFile != null) {//删除临时文件uploadFile.delete();}}}/*** 获取上传的文件* @param file* @return* @throws Exception*/private static File getUploadFile(MultipartFile file) throws Exception {if (file ==null) {throw new Exception("上传文件不能为空");}String filename = file.getOriginalFilename();String suffixName = filename.substring(filename.lastIndexOf("."));String filePath ="D:\\temp\\";long l = System.currentTimeMillis();File file1=new File(filePath+l+suffixName);if (!file1.exists() && !file1.isDirectory()) {file1.mkdirs();}file.transferTo(file1);return file1;}
}

2.请求实体类:

package com.zyp.model.dto;import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;import javax.validation.constraints.NotBlank;@Data
public class QRCodeDto {@NotBlank(message = "二维码内容不能为空")@ApiModelProperty("二维码内容")private String content;@ApiModelProperty("logo图片")private MultipartFile logoFile;@ApiModelProperty("二维码下方文字")private String pressText;
}

3.生成二维码

postman调试:

结果:

4.解析二维码

接口请求:

结果:

java生成与解析二维码 支持插入图片与文字相关推荐

  1. java生成以及解析二维码

    java生成以及解析二维码 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题,有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 ...

  2. Java生成和解析二维码工具类(简单经典)

    Java生成和解析二维码工具类 开箱即用,简单不废话. pom.xml引入依赖 <!-- https://mvnrepository.com/artifact/com.google.zxing/ ...

  3. Java生成与解析二维码

    1.下载支持二维码的jar包qrcode.jar和qrcode_swetake.jar, 其中qrcode_swetake.jar用于生成二维码,rcode.jar用于解析二维码,jar包下载地址(免 ...

  4. Java生成和解析二维码

    前言:曾经有做过不少微信公众号和移动网站的项目,对二维码还算有点了解,刚收到这个任务的时候就想着竟然要用二维码存文本,那就得先考究一下这小小的二维码到底能存多少的东西了. 需求:使用二维码存放文本(x ...

  5. java生成和解析二维码实战——QRCode

    直接上代码,以下程序可直接运行: package qrcode;import java.awt.Color; import java.awt.Graphics2D; import java.awt.i ...

  6. java 生成、解析二维码并在二维码中添加样式

    https://blog.csdn.net/yxj13935213026/article/details/81017902

  7. java利用zxing来生成和解析二维码,支持中文

    java在二维码的生成和解析上,网上有些人说如果要解析中文,得去修改工具包的Encoder类中的 static final String DEFAULT_BYTE_MODE_ENCODING = &q ...

  8. Java实现生成和解析二维码

    Java实现生成和解析二维码 文章目录 Java实现生成和解析二维码 一.建立项目 二.创建工具类 三.创建启动类 一.建立项目 首先需要创建一个普通的 Maven 项目,在这里我用的是 google ...

  9. 使用zxing生成与解析二维码

    随着二维码的普及,二维码在生活中的使用使用的场景也越来越来多,本文章就来介绍使用zxing来生成与解析二维码.生成二维码的开源项目很多,选择zxing则是因为其出自Google并且长期有人进行维护,值 ...

最新文章

  1. WinSock学习笔记3:Select模型
  2. 再见Xshell!这个开源的终端工具更酷炫!
  3. [其它] - 为什么中国的程序员技术偏低
  4. (36)FPGA三种基本逻辑门(与门)
  5. 代码审查清单 Code Review
  6. 不愧是我,短短10分钟就为公司省下了几万块 ( ー̀◡ー́ )
  7. 驱动开发:实现驱动加载卸载工具
  8. 软考中级软件设计师——数据库系统
  9. 一种简单的电荷泵驱动NMOS管电路
  10. c语言课程终结考试,C语言课程考核方案.doc
  11. c++笔记(超详细超完整)
  12. hanmming窗和hamming窗的作用
  13. ubuntu U盘只读的修复办法
  14. C++的errorC2039
  15. STM32 Cube MX学习笔记——TOF 高速单线激光雷达 L10(usart)
  16. 苹果cms模板_9ccms与苹果cms介绍.推荐小白用9ccms程序
  17. 用户标签体系的应用——精准营销
  18. Zhong__Docker安装和简单使用
  19. 数据结构之稀疏数组队列
  20. 将word文件中的文本转成字符串

热门文章

  1. 【图片修复】马赛克变高清
  2. 开源OA:手把手教你搭建OA办公系统(4)搭建报销审批流程
  3. java jsp网页新闻_JSP新闻显示
  4. SecureCRT取消错误提示音
  5. 学计算机方面该怎样保养眼睛,操作电脑时该怎样保护眼睛
  6. 第2讲 程序设计语言及其文法
  7. # 云计算建筑技术实践
  8. 同步通信与异步通信的主要区别
  9. 如何成为一名合格的前端工程师
  10. bl小说里面有个机器人管家_有机器人管家也别扔掉烫衣板