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

article/2025/9/23 22:51:06

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

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

第一步:导入相关的包

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();}}}

复制代码

运行测试了,效果图

 来源:https://www.cnblogs.com/Reborn-yuan/p/10409693.html


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

相关文章

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…

AVD的安装和配置

一、创建配置AVD 运行Eclipse &#xff0c;选择“window->Android Virtual Device Manager”&#xff1b;或者运行C盘根目录下的android-sdk-windows文件夹中的文件AVD Manager.exe&#xff0c;弹出一个对话框&#xff0c; 点击“New...”按钮&#xff0c;在弹出的对话框中…

【原理图】电路中的VCC VDD VSS VEE GND含义 以及STM32电源

原理图中经常出现的VCC VDD VSS VEE GND是什么意思呢&#xff1f; 总的来说 VDD&#xff0c;是Virtual Device Driver的缩写 VCC&#xff0c;是Volt Current Condenser的简写 GND 接地 他们的命名来自于MOS管和晶体管的接法&#xff0c;这个以后再提。 VCC vcc一般表示通用芯…

RK3566调试GC2053

电路 RK3566主板外接了一个MIPI接口涉嫌头模组&#xff0c;I2C接口I2C2&#xff0c;模组Sensor为GC2053&#xff0c;模组的设备地址为0x37&#xff08;地址需和模组厂家确定&#xff09;&#xff0c;电路如下&#xff1a; 管脚连接关系如下&#xff1a; GPIO0_C1------>CA…

微雪树莓派PICO笔记——4. ADC(模拟数字转换器)

文章目录 什么是ADCRP2040 ADC技术参数ADC大致框架图【MicroPython】machine.ADC类函数详解代码实现 如果我们需要使用PWM精准的控制LED的亮度&#xff0c;就需要反馈但是LED的亮度是一个模拟变量&#xff0c;MCU不能直接处理模拟信号我们需要将其转换为数字信号才能进行处理 …

TFT-LCD电路设计之电源电路(Power IC)

POWER IC REVIEWS Power IC 利用经系统的输入电压生成5种工作电压&#xff0c;一般外界电压&#xff0c;NB为3.3V&#xff0c;Monitor为5V&#xff0c;TV一般为12V&#xff1b; ①VDD&#xff1a;各种逻辑IC电路工作电压&#xff0c;约3.3V左右&#xff0c;一般采用低压差线性…

MTK 安卓11 lcm AVDD及AVEE值修改

通常情况下lcm的avdd默认5.4v&#xff0c;某些屏幕对avdd要求不同&#xff0c;需要进行修改 驱动程序路径&#xff1a; kernel-4.14/drivers/misc/mediatek/lcm/lcm_pmic.c int display_bias_enable(void) {int ret 0;int retval 0;display_bias_regulator_init();/* set v…

LCD VGH -VGL

此电路可以输出AVDD电压&#xff1a;1.25*&#xff08;56.210&#xff09;/108.275V LX用于VGH 、 VGL&#xff1a;为了理解方便&#xff0c;下面将LX视为&#xff1a;0到10V&#xff0c;100khz&#xff0c;100%占空比的方波输出&#xff0c;二极管的压差视为VF1V VGL解析&…

TFT供电电路(VCOM/VGL/VGH/AVDD)设计原理

一般而言&#xff0c;一个 LCD 需要以下几种驱动电压&#xff1a; VCC – TFT 模组数字模块电源 AVDD – TFT 模组模拟模块电源 &#xff0c;电流要求可能会到20-30mA VGH – 门开启电压&#xff0c;一般为 VGH 12V~25V&#xff0c;IVGH<10mA VGL – 门关断电压&…

Standard EVB硬件开发指南(1)——LCD接口电路

Standard EVB硬件开发指南 一、LCD接口电路详解1、VLED背光驱动电路2、LCD多电源管理器&#xff08;VCOM、VGH、VGL、AVDD&#xff09;3、MIPI、LVDS接口定义4、LVDS显示控制接口5、LCD Layout设计要求 一、LCD接口电路详解 Standard EVB具备6.8寸和7寸MIPI接口电路&#xff0…

科学计算工具IPython

IPython是公认的现代科学计算中最重要的Python 工具之一&#xff0c;它是一个加强版的Pvthon交互式命令行工具&#xff0c;与系统自带的Python 交互环境相比,IPython主要具有以下特点&#xff1a; 与Shell 紧密关联&#xff0c;可以在IPython开发环境下直接执行Shell指令。 它是…

Python:ipython进阶学习

文章目录 简介一、ipython与matplotlib结合二、jupyter qtconsole三、命令历史记录与输入输出四、ipython与操作系统进行交互五、高级功能小结 简介 前面讲解了ipython里面的一些核心知识点&#xff0c;包括它的优势所在、快捷键操作、内省、什么是魔术命令等等&#xff0c;本…

[转]IPython介绍

1. IPython介绍 ipython是一个python的交互式shell&#xff0c;比默认的python shell好用得多&#xff0c;支持变量自动补全&#xff0c;自动缩进&#xff0c;支持bash shell命令&#xff0c;内置了许多很有用的功能和函数。学习ipython将会让我们以一种更高的效率来使用python…

ipython学习

用pip安装ipython:pip install ipython 在开始菜单输入cmd&#xff0c;回车或者shift鼠标右键&#xff0c;选择‘在此处打开命令窗口’ -->输入ipython tab自动完成 内省 在变量的前面或后面加上一个问号(?)就可以将有关该对象的一些通用信息显示出来。这就叫做对象的内省…

Ipython版本控制

Ipython版本控制 2020-5-28 昨天设置了Anaconda环境的复制和移植&#xff0c;今天发现激活复制后的anaconda环境&#xff0c;ipython还是base版本的&#xff0c;python却已经转为了复制后的anaconda版本。 这说明ipython的控制和python控制还不是同步的&#xff0c;ipython需…

ipython安装报错

ipython安装报错 在命令行中执行 pip install ipython 安装报错 WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] 系统找不到指定的文件。: ‘C:\Python311\Scripts\pygmentize.ex…