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

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

第一步:导入相关的包

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

运行测试了,效果图

 

使用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. java springboot生成二维码图片

    java生成二维码图片 Maven依赖 <!--生成二维码--> <dependency><groupId>com.google.zxing</groupId ...

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

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

最新文章

  1. 物体抓取位姿估計算法綜述_大盘点|6D姿态估计算法汇总(上)
  2. 整合spring cloud云架构 - Gateway的基本入门
  3. shiro+redis多次调用doReadSession方法的解决方案
  4. [Bzoj2120]数颜色
  5. 实操教程|Pytorch - 弹性训练极简实现( 附源码)
  6. Universal Radio Hacker(URH):一个用于逆向解析和攻击无线通信协议的开源工具
  7. uniapp获取屏幕宽度的方式_Vue.js Uniapp 获取屏幕、元素的高度宽度
  8. 服务器为什么经常掉线?
  9. Linux下制作WIndows 7启动U盘
  10. Codeforces 1016C Vasya And The Mushrooms(动态规划)
  11. scrapy爬虫入门
  12. 数据基础---《利用Python进行数据分析·第2版》第11章 时间序列
  13. 如何按数字或者日期时间顺序对多个文件夹进行批量重命名?
  14. ansible的使用
  15. SEED-XDS560v2 EMU1-3 led闪烁
  16. 如何从亚马逊抓取产品数据?
  17. 尝试EFM32下的fatfs的使用
  18. python里的demo是什么意思_软件中的“DEMO” 是什么意思?游戏中的“DEMO呢?
  19. mysql-router设置,mysql router 中间件 配置
  20. rgb和rgba的区别关系

热门文章

  1. 【软件测试】室内设计师转软件测试,拿下高薪15K,众人惊呆了
  2. Lab 6: Network Driver (default final project)
  3. mysql气象数据分析_气象行业 - 解决方案 - MySQL分布式数据库_开源数据库解决方案_数据处理技术提供商-爱可生...
  4. android 6 华为,6.1英寸Android:华为Mate
  5. 数字孪生钢铁行业研究案例
  6. 小熊U租获联想创投战略投资,会是一场双赢牌局吗?
  7. 目前Java开发前景还好吗 Java工资待遇怎么样
  8. 响应式开发:登录界面实现
  9. Linux内核符号及地址
  10. 计算机网络私有地址吗,公有IP地址与私有IP地址有什么不同?