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

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

第一步:导入相关的包

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

使用Java生成二维码图片(亲测)相关推荐

  1. 使用Java生成二维码图片

    下面我来分享两种生成二维码图片的方法. 第一种,填入你扫描二维码要跳转的网址直接生成二维码 第一步:导入相关的包 1 <dependency> 2 <groupId>com.g ...

  2. Java - 生成二维码图片

    文章目录 生成二维码图片 参考 生成二维码图片 新建 Maven Project,引入依赖: <dependency><groupId>com.google.zxing< ...

  3. java生成二维码图片(有logo),并在图片下方附文字

    logo配置类 /*** Created by Amber Wang on 2017/11/27 17:25.*/import java.awt.*;public class LogoConfig { ...

  4. java生成二维码图片、转base64

    本文介绍通过java把文字或url生成二维码,使用浏览器或者微信扫一扫即可获得文字或url内容,超简单的方法,两个步骤复制粘贴即可使用. 注意:内容是文字会直接显示,如果内容为url地址那么会直接访问 ...

  5. springboot+java生成二维码图片

    接下来将从IDEA创建springboot项目到生成效果图详细地为大家展示二维码的制作过程 1.首先是创建springboot项目 上面的图有红色标记的地方需要填写的,比如项目存放的路径,包名等,其他 ...

  6. JAVA 生成二维码图片 可加Logo

    现在二维码在很多地方有运用,在这里写一份简洁明快的代码,方便以后使用.有需要的朋友可以直接复制过去 直接使用 所需要的jar:QRCode.jar jar下载地址:点击打开链接 package QrC ...

  7. Java生成二维码图片,手机软件扫码后跳转网页

    一.创建maven工程,添加如下依赖 <dependencies><dependency><groupId>com.google.zxing</groupId ...

  8. 前端页面直接根据URL链接生成二维码【亲测可用】

    1安装qrcodejs2 npm install qrcodejs2 -save 实操:Terminal下执行 2在所需要的前端页面中引入[找到qrcode.js直接拉到页面中] 或者 import ...

  9. Java生成二维码带LOGO底部标题竖版字体

    前言 Java后端生成二维码 底部 侧面带有标题,可调节字号 参考文章 使用Java生成二维码图片(亲测) Reborn_YY使用Java生成二维码图片 图标素材库 Java后台生成图片,前台实现图片 ...

最新文章

  1. Node.js + Express 4.x + MongoDB 构建登录注册-简易用户管理(四)
  2. 「golang」panic: commands out of sync. Did you run multiple statements at once
  3. 前端小姐姐助你俘获女神心,双十一挑口红神器在此 | 开源项目
  4. 学python语言用什么软件-Python是什么?学习Python用什么编译器?
  5. Android 3.0 r1中文API文档(104) —— ViewTreeObserver
  6. Wince下定制开机自启动程序
  7. Flask实战1-轻博客
  8. Codeforces 722C. Destroying Array
  9. 洛谷-图的遍历-P2661-信息传递
  10. python ---ConfigParser
  11. uBLAS——Boost 线性代数基础程序库 (三)
  12. Graham-Scan小总结——toj2317 Wall
  13. 用例图中三种关系详解(转)
  14. 华为手机序列号前三位_华为手机SN码里隐藏的秘密,选购手机必备冷知识!
  15. vue博客模板—Fblog
  16. TCP/IP协议及常见状态码(SYN,FIN,ACK,PSH,RST)
  17. 加班到凌晨三点?一张图看懂华为员工睡眠时间!!
  18. 1.1 win10下wget的安装
  19. java_异常_练习题:处理输入非数字异常和除数为0的异常。
  20. android app源码大全_[源码和文档分享]基于Android的家庭学校联系平台APP开发与实现...

热门文章

  1. np.insert()
  2. 计算机组成原理 外部设备分为,2017考研计算机组成原理第七章考点:外部设备...
  3. c语言将结果原模原样输出到文件,2013年9月全国计算机二级C语言程序设计上机模考试卷1.docx...
  4. B03_NumPy创建数组(numpy.empty,numpy.zeros,numpy.ones)
  5. 模拟使用Flume监听日志变化,并且把增量的日志文件写入到hdfs中
  6. System.getProperty()的用途
  7. Linux sed 写命令常见使用案例
  8. mediawiki java_使用MediaWiki 1.16.0实现添加媒体向导
  9. 几款不错的VisualStudio2010插件
  10. 设备的阻塞与非阻塞操作