使用java生成QRCode二维码

需要引入zxing依赖:

<!--   google zxing qrcode生成依赖  -->
<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.0</version>
</dependency>
<dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.3.0</version>
</dependency>

生成二维码

/*** @author liuminkai* @version 1.0* @datetime 2021/1/27 15:02* @decription zxing生成**/
public class CreateQRCode {public static void main(String[] args) {// vCard2.1String content = "BEGIN:VCARD"+"\n"+"VERSION:2.1"+"\n"+"N:姓;名"+"\n"+"FN:姓名"+"\n"+"NICKNAME:nickName"+"\n"+"ORG:公司;部门"+"\n"+"TITLE:职位"+"\n"+"TEL;WORK;VOICE:电话1"+"\n"+"TEL;WORK;VOICE:电话2"+"\n"+"TEL;HOME;VOICE:电话1"+"\n"+"TEL;HOME;VOICE:电话2"+"\n"+"TEL;CELL;VOICE:13590342862"+"\n"+"TEL;PAGER;VOICE:0755"+"\n"+"TEL;WORK;FAX:传真"+"\n"+"TEL;HOME;FAX:传真"+"\n"+"ADR;WORK:;;单位地址;深圳;广东;433000;国家"+"\n"+"ADR;HOME;POSTAL; PARCEL:;;街道地址;深圳;广东;433330;中国"+"\n"+"URL:网址"+"\n"+"URL:单位主页"+"\n"+"EMAIL;PREF;INTERNET:邮箱地址"+"\n"+"X-QQ:11111111"+"\n"+"END:VCARD" ;createQRCode(content);}public static void createQRCode(String content){createQRCode(content, "QRCode.png");}public static void createQRCode(String content, String fileName){createQRCode(content, 500, 500, "png", fileName);}/*** 二维码生成* @date 2021/1/27 15:34* @param content 内容* @param width 宽* @param height 高* @param format 图片格式* @param fileName 生成图片的文件名* @return void**/public static void createQRCode(String content, int width, int height, String format, String fileName){// 二维码配置Map hints = new HashMap();hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 二维码编码utf-8hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 纠错级别(L < M < Q < H) 级别越高,存储数据越少hints.put(EncodeHintType.MARGIN, 1); // 外边框大小// 生成二维码try {BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);Path file = new File(fileName).toPath();MatrixToImageWriter.writeToPath(bitMatrix, format, file);} catch (Exception e) {e.printStackTrace();}}
}

运行程序,会在项目根目录下生成 QRCode.png图片

解析二维码

/*** @author liuminkai* @version 1.0* @datetime 2021/1/27 15:46* @decription 解析二维码**/
public class ReadQRCode {public static void main(String[] args) throws IOException, NotFoundException {System.out.println("解析的结果: \n " + readQRcode());}/*** 解析二维码* @date 2021/1/27 15:51* @return java.lang.String**/public static String readQRcode() throws NotFoundException, IOException {MultiFormatReader multiFormatReader = new MultiFormatReader();Map hints = new HashMap();File file = new File("QRCode.png");hints.put(DecodeHintType.CHARACTER_SET, "utf-8");BufferedImage bufferedImage = ImageIO.read(file);BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));Result result = multiFormatReader.decode(binaryBitmap, hints);System.out.println(result);System.out.println("内容 : " + result.getText());System.out.println("编码格式 : " + result.getBarcodeFormat());return result.toString();}
}

运行程序,控制台输出解析结果:

二维码工具类

将上述二维码生成和解析进行封装,并添加带logo的二维码生成

package xyz.liuyou.zxing;import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import xyz.liuyou.zxing.utils.QRCodeUtil;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;/*** @author liuminkai* @version 1.0* @datetime 2021/1/27 22:35* @decription 二维码工具类**/
public class QRCodeUtils {/*** 字符集*/private static final String CHARSET = "UTF-8";/*** 二维码尺寸 长宽*/private static final int QRCODE_SIZE = 400;/*** 生成二维码图片的格式*/private static final String FORMAT = "jpg";/*** logo宽*/private static final int LOGO_WIDTH = QRCODE_SIZE/5;/*** logo高*/private static final int LOGO_HEIGHT = QRCODE_SIZE/5;/*** 设置 二维码 1 代表色 : 默认 0xFF000000 黑*/private static final int ONE_COLOR = 0xFF000001;
//    private static final int ONE_COLOR = 0xFFFF0000; // 红/*** 设置 二维码 0 代表色 : 默认 0xFFFFFFFF 白*/private static final int ZERO_COLOR = 0xFFFFFFFF;public static void createQRCode(String content, String outputPath) throws IOException {createQRCode(content, new FileOutputStream(outputPath));}public static void createQRCode(String content, File outputFile) throws IOException {createQRCode(content, new FileOutputStream(outputFile));}/*** 创建原始二维码(不带logo)* @param content 二维码内容* @param output 二维码(文件)输出流* @return void**/public static void createQRCode(String content, OutputStream output) {try {ImageIO.write(createQRCodeImage(content), FORMAT, output); // 关键类 ImageIOoutput.close();} catch (IOException | WriterException e) {e.printStackTrace();}}public static void createQRCodeWithLogo(String content, String outputPath, String logoPath) throws IOException {createQRCodeWithLogo(content, new FileOutputStream(outputPath), logoPath, true);}public static void createQRCodeWithLogo(String content, String outputPath, String logoPath, boolean needCompress) throws IOException {createQRCodeWithLogo(content, new FileOutputStream(outputPath), logoPath, needCompress);}public static void createQRCodeWithLogo(String content, File outputFile, String logoPath, boolean needCompress) throws IOException {createQRCodeWithLogo(content, new FileOutputStream(outputFile), logoPath, needCompress);}/*** 创建二维码(带logo)* @param content* @param output* @param logoPath logo路径(可以是resources路径)* @param needCompress 是否需要压缩logo* @return void**/public static void createQRCodeWithLogo(String content, OutputStream output, String logoPath, boolean needCompress) {try {// 创建image对象BufferedImage qrcodeImage = createQRCodeImage(content);BufferedImage logoImage = createLogoImage(logoPath);// 压缩logoif(needCompress) {logoImage = compressLogoImage(logoImage);}// 绘制logo二维码BufferedImage newImage = drawLogoQRCode(qrcodeImage, logoImage);// 生成ImageIO.write(newImage, FORMAT, output);output.close();} catch (WriterException | IOException e) {e.printStackTrace();}}/*** 解析qrcode二维码图片* @param qrcodePath 二维码路径* @return java.lang.String* @throw IOException, NotFoundException**/public static String parseQRCode(String qrcodePath) throws IOException, NotFoundException {Map<DecodeHintType, Object> hints = new HashMap<>();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);BufferedImage image = ImageIO.read(new File(qrcodePath));MultiFormatReader multiFormatReader = new MultiFormatReader(); // 主要对象 ===========Result result = multiFormatReader.decode(new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image))), hints);return result.toString();}/*** (私有)创建二维码图像对象* @param content 二维码内容* @return java.awt.image.BufferedImage* @throw WriterException**/private static BufferedImage createQRCodeImage(String content) throws WriterException {if (content == null) {throw new NullPointerException("createQRCodeImage(String content) : content不能为null");}Map<EncodeHintType, Object> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, CHARSET); // 字符集hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 纠错级别,级别越高存储数据越少hints.put(EncodeHintType.MARGIN, 1); // 外边框MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); // ====== 主要对象BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);// 编码 生成矩阵对象MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(ONE_COLOR, ZERO_COLOR); // 配置 二维码颜色return MatrixToImageWriter.toBufferedImage(bitMatrix, matrixToImageConfig); // 生成图像对象(注意要设置颜色,且不能是默认的,不然使用不了rgb绘制图像,也就是黑白色)}/*** (私有)创建logo图像对象* @param logoPath* @return java.awt.image.BufferedImage* @throw IOException**/private static BufferedImage createLogoImage(String logoPath) throws IOException {InputStream is = QRCodeUtil.class.getClassLoader().getResourceAsStream(logoPath);if (is == null) {is = new FileInputStream(logoPath);}BufferedImage logoImage = ImageIO.read(is);is.close();return logoImage; // 关键类 ImageIO}/*** (私有)压缩logo,返回新的logo图像对象 (防止图片过大缩放质量差)* @param logoImage* @return java.awt.image.BufferedImage**/private static BufferedImage compressLogoImage(BufferedImage logoImage) {// 获取logo原始图片宽高int originalHeight = logoImage.getHeight();int originalWidth = logoImage.getWidth();// 压缩logo (宽高都是选择最小的)int height = originalHeight > LOGO_HEIGHT ? LOGO_HEIGHT : originalHeight;int width = originalWidth > LOGO_WIDTH ? LOGO_WIDTH : originalWidth;// 获取缩放Image scaledInstance = logoImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 创建画笔Graphics2D graphics = newImage.createGraphics();// 绘制压缩后的logographics.drawImage(scaledInstance, 0, 0, width, height, null);graphics.dispose();return newImage;}/*** (私有)绘制logo二维码* @param qrcodeImage* @param logoImage* @return void**/private static BufferedImage drawLogoQRCode(BufferedImage qrcodeImage, BufferedImage logoImage) {// 获取画笔对象Graphics2D graphics = qrcodeImage.createGraphics();int logoX = (QRCODE_SIZE - LOGO_WIDTH) / 2;int logoY = (QRCODE_SIZE - LOGO_HEIGHT) / 2;// 绘制logo到qrcode上graphics.drawImage(logoImage, logoX, logoY, LOGO_WIDTH, LOGO_HEIGHT, null);// 绘制logo边框(圆弧框)Shape round = new RoundRectangle2D.Float(logoX-2, logoY-2, LOGO_WIDTH+2, LOGO_HEIGHT+2, 10, 10);graphics.setStroke(new BasicStroke(5f)); // 宽度graphics.setColor(Color.LIGHT_GRAY);graphics.draw(round);// 销毁画笔graphics.dispose();return qrcodeImage;}public static void main(String[] args) throws IOException, WriterException, NotFoundException {String content = "中文。。。。。。。。。。。。。。。。。。。。。。。";QRCodeUtils.createQRCodeWithLogo(content, "logoqrcode.jpg", "author.jpg");QRCodeUtils.createQRCode(content, "qrcode.jpg");System.out.println("qrcode.jpg 被解析为:" + parseQRCode("qrcode.jpg"));System.out.println("logoqrcode.jpg 被解析为:" + parseQRCode("logoqrcode.jpg"));}
}

测试结果展示:

2021-1-26-java生成二维码相关推荐

  1. java 生成二维码,解析二维码

    今天遇到需求,使用Java生成二维码图片,网搜之后,大神们早就做过,个人总结一下. 目标:借助Google提供的ZXing Core工具包,使用Java语言实现二维码的生成和解析. 步骤如下: 1.m ...

  2. Java生成二维码底部带文字并且返回前端使用img接收

    目录 1.java生成二维码工具类 2.web测试 3.前端处理 4.测试结果 背景 本demo主要针对jdk1.6版本的,但是高版本的同样可以用,如果觉得不舒服可以自行添加高版本的依赖包. 准备工具 ...

  3. java 生成二维码 QRCode、zxing 两种方式

    版权声明:本文为 testcs_dn(微wx笑) 原创文章,非商用自由转载-保持署名-注明出处,谢谢. https://blog.csdn.net/testcs_dn/article/details/ ...

  4. 二维码相关---java生成二维码名片,并且自动保存到手机通讯录中...

    二维码相关---java生成二维码名片,并且自动保存到手机通讯录中... 技术qq交流群:JavaDream:251572072 1.首先介绍一个api.   Zxing是Google提供的关于条码 ...

  5. java生成二维码打印到浏览器

    java生成二维码打印到浏览器 解决方法: pom.xml的依赖两个jar包: <!-- https://mvnrepository.com/artifact/com.google.zxing/ ...

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

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

  7. java生成二维码,并在前端展示。

    java生成二维码,并在前端展示,扫码实现下载功能. 后端生成二维码以流的形式 前端接收二维码并展示 后端生成二维码以流的形式 这是以流的形式展示二维码.当然也可以以文件的格式,文件格式就是Path ...

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

    Java二维码如何生成? awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import com. ...

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

    java生成二维码到文件,java生成二维码转成BASE64 如题,利用java和第三方库,把指定的字符串生成二维码,并且把二维码保存成图片,转换成BASE64格式. 需要的jar文件: packag ...

  10. java生成二维码扫描跳转到指定的路径URL

    java生成二维码扫描跳转到指定的路径URL 导入依赖 <dependency><groupId>com.google.zxing</groupId><art ...

最新文章

  1. UI设计培训分享:设计当中的颜色运用
  2. Atom介绍和安装步骤
  3. 开发日记-20190821 关键词 读书笔记《掌控习惯》DAY 1
  4. laravel路由无法访问,报404,No query results for model [App\Models\...]
  5. MyBatis及Spring事务初学总结
  6. cfiledialog指定位置和大小_GDamp;T | 位置度公差的理解过程
  7. Java集合Stream类
  8. [转载] Java:获取数组中的子数组的多种方法
  9. 如何将DB2数据库转换成Oracle数据库,这一篇告诉你
  10. vb 获取系统声音的电平_专业音响系统中常见问题,看看你懂几个?
  11. pytorch学习笔记(三十七):RMSProp
  12. 你以为用了 BigDecimal 后,计算结果就一定精确了?
  13. db2电话号码加密脚本
  14. 04_过滤器Filter_04_Filter生命周期
  15. cocos2d学习之路四(添加遥控杆)
  16. android+接入易宝支付,iOS客户端连接易宝支付接口
  17. 小葵花妈妈课堂之Nginx Rewirte
  18. 手机端 19FPS 的实时目标检测算法:YOLObile
  19. java徽章_java – 设计可插拔的点和徽章系统
  20. linux的passive用法,get的被动用法(get-passive)

热门文章

  1. 0基础单片机入门知识:怎么使用数字万用表以及注意事项
  2. dex字符串解密_某Xposed微信群发工具dex解密分析
  3. 【零基础强化学习】100行代码教你训练——基于SARSA的CliffWalking爬悬崖游戏
  4. COMBINING LABEL PROPAGATION AND SIMPLE MODELS OUT-PERFORMS GRAPH NEURAL NETWORKS(CorrectSmooth)阅读笔记
  5. 21 python - 字典
  6. 计算机服务器属无形资产吗,服务器属于固定资产还是无形资产
  7. DolphinPHP 框架wangeditor编辑器图片路径改为绝对链接
  8. 给的再多,不如懂我——Gif录制工具,这两个就够了
  9. 获取用户微信头像 高清大图
  10. 公主连结显示服务器内部错误,公主连结Re:Dive无法连接服务器是什么原因