使用Java生成二维码图片

article/2025/9/23 21:38:39

下面我来分享两种生成二维码图片的方法。

第一种,填入你扫描二维码要跳转的网址直接生成二维码

第一步:导入相关的包

1 <dependency>
2     <groupId>com.google.zxing</groupId>
3     <artifactId>core</artifactId>
4     <version>3.3.3</version>
5 </dependency>

第二步:配置图像写入器类

复制代码

 1 package com.easycare.util.twocode;2 3 import java.awt.image.BufferedImage;4 import java.io.File;5 import java.io.IOException;6 7 import javax.imageio.ImageIO;8 9 import com.google.zxing.common.BitMatrix;
10 
11 /**
12  * 配置图像写入器
13  * 
14  * @author 18316
15  * 
16  */
17 public class MatrixToImageWriter {
18     private static final int BLACK = 0xFF000000;
19     private static final int WHITE = 0xFFFFFFFF;
20 
21     private MatrixToImageWriter() {
22     }
23 
24     public static BufferedImage toBufferedImage(BitMatrix matrix) {
25         int width = matrix.getWidth();
26         int height = matrix.getHeight();
27         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
28         for (int x = 0; x < width; x++) {
29             for (int y = 0; y < height; y++) {
30                 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
31             }
32         }
33         return image;
34     }
35 
36     public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
37         BufferedImage image = toBufferedImage(matrix);
38         if (!ImageIO.write(image, format, file)) {
39             throw new IOException("Could not write an image of format " + format + " to " + file);
40         }
41     }
42 
43 }

复制代码

第三步:测试类

复制代码

package com.easycare.util.twocode;import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;public class MyTest {public static void main(String[] args) {System.out.println("开始生成...");code();System.out.println("生成完毕!");}public static void code() {try {String content = "https://www.baidu.com";String path = "G:/测试";// 二维码保存的路径String codeName = UUID.randomUUID().toString();// 二维码的图片名String imageType = "jpg";// 图片类型MultiFormatWriter multiFormatWriter = new MultiFormatWriter();Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);File file1 = new File(path, codeName + "." + imageType);MatrixToImageWriter.writeToFile(bitMatrix, imageType, file1);} catch (WriterException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

复制代码

好了第一种二维码生成功能写好了,点击运行测试类,下面给出效果图,因为我的代码写的是二维码保存在G:/测试,所以到G盘中找到图片

 

扫描之后就能跳转到我写入的百度地址。

 

第二种生成二维码的方法,这种相比上一种能在生成的二维码中插入个性logo

第一步:导入相关的包

1 <dependency>
2     <groupId>com.google.zxing</groupId>
3     <artifactId>core</artifactId>
4     <version>3.3.3</version>
5 </dependency>

第二步:继承LuminanceSource类

复制代码

 1 package com.easycare.util.imagecode;2 3 import java.awt.Graphics2D;4 import java.awt.geom.AffineTransform;5 import java.awt.image.BufferedImage;6 7 import com.google.zxing.LuminanceSource;8 9 public class BufferedImageLuminanceSource extends LuminanceSource {
10     private final BufferedImage image;
11     private final int left;
12     private final int top;
13 
14     public BufferedImageLuminanceSource(BufferedImage image) {
15         this(image, 0, 0, image.getWidth(), image.getHeight());
16     }
17 
18     public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
19         super(width, height);
20         int sourceWidth = image.getWidth();
21         int sourceHeight = image.getHeight();
22         if (left + width > sourceWidth || top + height > sourceHeight) {
23             throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
24         }
25         for (int y = top; y < top + height; y++) {
26             for (int x = left; x < left + width; x++) {
27                 if ((image.getRGB(x, y) & 0xFF000000) == 0) {
28                     image.setRGB(x, y, 0xFFFFFFFF); // = white
29                 }
30             }
31         }
32         this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
33         this.image.getGraphics().drawImage(image, 0, 0, null);
34         this.left = left;
35         this.top = top;
36     }
37 
38     @Override
39     public byte[] getRow(int y, byte[] row) {
40         if (y < 0 || y >= getHeight()) {
41             throw new IllegalArgumentException("Requested row is outside the image: " + y);
42         }
43         int width = getWidth();
44         if (row == null || row.length < width) {
45             row = new byte[width];
46         }
47         image.getRaster().getDataElements(left, top + y, width, 1, row);
48         return row;
49     }
50 
51     @Override
52     public byte[] getMatrix() {
53         int width = getWidth();
54         int height = getHeight();
55         int area = width * height;
56         byte[] matrix = new byte[area];
57         image.getRaster().getDataElements(left, top, width, height, matrix);
58         return matrix;
59     }
60 
61     @Override
62     public boolean isCropSupported() {
63         return true;
64     }
65 
66     @Override
67     public LuminanceSource crop(int left, int top, int width, int height) {
68         return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
69     }
70 
71     @Override
72     public boolean isRotateSupported() {
73         return true;
74     }
75 
76     @Override
77     public LuminanceSource rotateCounterClockwise() {
78         int sourceWidth = image.getWidth();
79         int sourceHeight = image.getHeight();
80         AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
81         BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
82         Graphics2D g = rotatedImage.createGraphics();
83         g.drawImage(image, transform, null);
84         g.dispose();
85         int width = getWidth();
86         return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
87     }
88 }

复制代码

 

第三步:配置图像写入器类

复制代码

package com.easycare.util.imagecode;import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import java.util.UUID;import javax.imageio.ImageIO;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/*** 二维码生成类* * @author 18316**/
public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "jpg";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int WIDTH = 100;// LOGO高度private static final int HEIGHT = 100;private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,hints);int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();BufferedImage image = new BufferedImage(width, height, 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);}}if (imgPath == null || "".equals(imgPath)) {return image;}// 插入图片QRCodeUtil.insertImage(image, imgPath, needCompress);return image;}/*** 插入LOGO* * @param source       二维码图片* @param imgPath      LOGO图片地址* @param needCompress 是否压缩* @throws Exception*/private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {File file = new File(imgPath);if (!file.exists()) {System.err.println("" + imgPath + "   该文件不存在!");return;}Image src = ImageIO.read(new File(imgPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = 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_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();}/*** 生成二维码(内嵌LOGO)* * @param content      内容* @param imgPath      LOGO地址* @param destPath     存放目录* @param needCompress 是否压缩LOGO* @throws Exception*/public static String encode(String content, String imgPath, String destPath, boolean needCompress)throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);mkdirs(destPath);// 随机生成二维码图片文件名String file = UUID.randomUUID() + ".jpg";ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));return destPath + file;}/*** 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)* * @author lanyuan Email: mmm333zzz520@163.com* @date 2013-12-11 上午10:16:36* @param destPath 存放目录*/public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}}

复制代码

 

运行测试了,效果图

 

http://chatgpt.dhexx.cn/article/etAHwrg2.shtml

相关文章

java生成二维码工具

1&#xff0c;添加maven依赖 <!-- 生成二维码 --> <dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.4.1</version> </dependency> 2&#xff0c;微信支付宝图片 3&#x…

二维码是什么?java生成二维码

生成二维码的网站可用于测试&#xff1a;草料二维码 参考资料&#xff1a;二维码&#xff08;QR code&#xff09;基本结构及生成原理 二维码 &#xff08;2-dimensional bar code&#xff09;&#xff0c;是用某种特定的几何图形按一定规律在平面&#xff08;二维方向上&…

关于Java生成二维码(zxing)

使用zxing生成二维码 提示&#xff1a;需要自己添加执行zxing.jar包 操作:点击链接去下载zxing包。GitHub - zxing/zxing: ZXing ("Zebra Crossing") barcode scanning library for Java, Androidhttps://github.com/zxing/zxing/ 文章目录 前言一、zxing是什么&…

一步一步教你用 java 生成二维码

一步一步用java设计生成二维码 在物联网的时代&#xff0c;二维码是个很重要的东西了&#xff0c;现在无论什么东西都要搞个二维码标志&#xff0c;唯恐落伍&#xff0c;就差人没有用二维码识别了。也许有一天生分证或者户口本都会用二维码识别了。今天心血来潮&#xff0c;看见…

java生成二维码到文件,java生成二维码转成BASE64

java生成二维码到文件&#xff0c;java生成二维码转成BASE64 如题&#xff0c;利用java和第三方库&#xff0c;把指定的字符串生成二维码&#xff0c;并且把二维码保存成图片&#xff0c;转换成BASE64格式。 需要的jar文件&#xff1a; package com.xueyoucto.xueyou;import …

关于java生成二维码:QR Code

QR Code的生成和读取在两个文件&#xff1a; 生成&#xff1a;QRcode​​​​​qrcode encoder (cgi programs/libralies) , QRcode demo and document of how to createhttp://www.swetake.com/qrcode/index-e.html 读取&#xff1a; オープンソースのQRコードデコードライ…

JAVA-生成二维码图片

JAVA-生成二维码图片 有很多大佬写了&#xff0c;但是这种花里胡哨的活我最喜欢搞了 首先是依赖 官网地址&#xff1a;https://mvnrepository.com/artifact/com.google.zxing/core 一般找用的最多的&#xff0c;相对稳定&#xff0c;出问题了也肯定有大佬给出相对应的解决办…

原来Java生成二维码这么简单

文章目录 一、二维条码/二维码(2-dimensional bar code)的概念二、二维码的发展历史三、二维码的分类四、二维码的优缺点五、QR Code六、实例开发1、zxing生成二维码2、zxing进行二维码解析3、使用QR Code方式生成和解析二维码4、jquery-qrcode生成二维码 一、二维条码/二维码(…

java生成二维码,跳转到指定页面

一、介绍&#xff1a;生成二维码有很多种方法&#xff0c;比如微信公众号的生成二维码&#xff0c;但是这个二维码只能用微信扫描且会&#xff08;可以带参数&#xff09;自动跳转到微信的公众号页面&#xff0c;不支持跳转到其他网页。这里说的二维码是扫描&#xff08;微信、…

Java生成二维码(附工具类)

后台Java生成二维码 这里用到了谷歌的zxing包&#xff0c;maven依赖如下&#xff1a; <!-- 二维码依赖开始--><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.4.0</version></…

java生成二维码最简单方法

昨天接到了一个需求是通过jave服务端动态生成二维码&#xff0c;提供给前端调用&#xff0c;这里就介绍一下生成的过程。 我这里是一个springboot服务&#xff0c;springboot服务的jar包就不贴了 这里只粘贴二维码用到的依赖。 1、pom依赖&#xff0c;这里只用到了两个依赖 &…

java生成二维码(链接生成二维码)

Java二维码如何生成&#xff1f; awt。image。BufferedImage; import java。io。File; import javax。imageio。ImageIO; import com。swetake。util。Qrcode; public class QRCodeEncoderTest { public static void main(String[] args) throws Exception { Qrcode qrco…

JAVA生成二维码QRcode

JAVA生成二维码QRcode 1 : 配置集成1.1、配置maven1.2、配置文件1.3、logo文件 2 : 代码集成2.1、加载配置文件2.2、工具类2.3、测试类 3 : 测试结果3.1、生成二维码3.2、扫描结果3.3、资源 1 : 配置集成 1.1、配置maven pom文件中添加一下配置 <!-- QR code --> <…

Java实现生成二维码

前言&#xff1a; 目前所分享的技术栈为Javaweb之后学运用到的 有喜欢我分享的一些demo可以多多交流 生成二维码前提&#xff1a; 1.需要引入谷歌所推荐使用的jar包 2.此jar包名称叫做zxing&#xff0c;目前我还没找到能所下载的jar包 3.我这里有自己制作好的jar包可以云盘下…

使用Java生成二维码图片(亲测)

下面我来分享两种生成二维码图片的方法。 第一种&#xff0c;填入你扫描二维码要跳转的网址直接生成二维码 第一步&#xff1a;导入相关的包 1 <dependency> 2 <groupId>com.google.zxing</groupId> 3 <artifactId>core</artifactId>…

Java生成二维码的几种实现方式(基于Spring Boot)

本文将基于Spring Boot介绍两种生成二维码的实现方式&#xff0c;一种是基于Google开发工具包&#xff0c;另一种是基于Hutool来实现&#xff1b; 为了方便理解二维码的实际应用场景&#xff0c;举一些例子&#xff01; &#xff08;1&#xff09;进销存系统 想必大家都听说过…

RK3562 camera调试:MIPI资源和配置

这篇文章给大家介绍一下RK新的一颗RK3562的camera资源以及MIPI的配置。 目录 &#xff08;1&#xff09;RK3562 camera资源 ①RK3562 camera硬件框图 ②MIPI-CSI资源 ③VICAP资源 ④ISP资源 ⑤最多支持camera数量 &#xff08;2&#xff09;dts配置 &#xff08;3&…

电子设计入门——单片机最小系统

写在前面 本文以STM32F401RCT6为例&#xff0c;讲解单片机最小系统的设计方法&#xff0c;以及一些相关的原理。 上图所示即为单片机最小系统电路&#xff0c;我们将其分为三个部分&#xff0c;即电源电路、复位电路、时钟电路。在了解最小电路之前&#xff0c;我们先看看下面…

LCD/HDMI OUT调试经验(4)------点亮LCD

本文以最近在QCM6490平台调试的一块FT8719为例&#xff0c;详细介绍点亮一块LCD屏幕的完整过程。 点亮屏幕的操作主要分两部分&#xff1a;上电和配置MIPI参数。上电保证屏幕可以有正常的背光&#xff0c;而MIPI参数保证有合适的清晰度&#xff0c;分辨率和画面。 一、上电 拿…

AVD那些事儿

启动了AVD却说找不到AVD 错误提示&#xff1a; No active compatible AVDs or devices found. Relaunch this configuration after connecting a device o 查看你的project版本是运行在哪个版本的&#xff08;AndroidManifest.xml中android:targetSdkVersion属性&#xff09…