Java实现生成和解析二维码


文章目录

  • Java实现生成和解析二维码
    • 一、建立项目
    • 二、创建工具类
    • 三、创建启动类

一、建立项目

首先需要创建一个普通的 Maven 项目,在这里我用的是 google 提供的 jar包,pom.xml 文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.javaboy</groupId><artifactId>QRCode</artifactId><version>1.0-SNAPSHOT</version><dependencies><!-- 添加 google 提供的二维码依赖 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.0</version></dependency></dependencies>
</project>

如果maven没有反应,建议刷新一下或者更换maven源(这里用的就是阿里云源)

二、创建工具类

这里需要创建两个工具类BufferedImageLuminanceSourceQRCodeUtil类。项目结构如下,我创建的是springboot的jar包,当然其他的也都可以的。

工具类1 (BufferedImageLuminanceSource)

package com.csdn.qrcode.util;import com.google.zxing.LuminanceSource;import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;public class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white}}}this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);this.image.getGraphics().drawImage(image, 0, 0, null);this.left = left;this.top = top;}@Overridepublic byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}image.getRaster().getDataElements(left, top + y, width, 1, row);return row;}@Overridepublic byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];image.getRaster().getDataElements(left, top, width, height, matrix);return matrix;}@Overridepublic boolean isCropSupported() {return true;}@Overridepublic LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);}@Overridepublic boolean isRotateSupported() {return true;}@Overridepublic LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);Graphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();int width = getWidth();return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);}
}

工具类2 (QRCodeUtil)

这里面可以修改一些参数,例如二维码的尺寸,宽高等等。

package com.csdn.qrcode.util;import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;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 = 60;// LOGO高度private static final int HEIGHT = 60;private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {Hashtable hints = new Hashtable();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;}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();}public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);mkdirs(destPath);// String file = new Random().nextInt(99999999)+".jpg";// ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));ImageIO.write(image, FORMAT_NAME, new File(destPath));}public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);return image;}public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}public static void encode(String content, String imgPath, String destPath) throws Exception {QRCodeUtil.encode(content, imgPath, destPath, false);}// 被注释的方法/** public static void encode(String content, String destPath, boolean* needCompress) throws Exception { QRCodeUtil.encode(content, null, destPath,* needCompress); }*/public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);ImageIO.write(image, FORMAT_NAME, output);}public static void encode(String content, OutputStream output) throws Exception {QRCodeUtil.encode(content, null, output, false);}public static String decode(File file) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;Hashtable hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}}

三、创建启动类

这一步就是调用方法,一般大家使用这种功能都是为了实现业务,例如常见的扫描二维码跳转链接(页面),扫描二维码出现文字等等。有些二维码中间还带有 Logo 这种图片,将需要嵌入二维码的图片路径准备好就没有问题。

package com.csdn.qrcode;import com.csdn.qrcode.util.QRCodeUtil;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class QrcodeApplication {public static void main(String[] args) throws Exception {// 存放在二维码中的内容// 二维码中的内容可以是文字,可以是链接等String text = "http://www.baidu.com";// 嵌入二维码的图片路径// String imgPath = "C:\\Users\\Administrator\\Pictures\\img\\dog.jpg";String imgPath = "picture/lemon.jpg";// 生成的二维码的路径及名称String destPath = "picture/" + System.currentTimeMillis() + ".jpg";//生成不带logo的二维码// QRCodeUtil.encode(text, null, destPath, true);//生成带logo的二维码QRCodeUtil.encode(text, imgPath, destPath, true);// 解析二维码String str = QRCodeUtil.decode(destPath);// 打印出解析出的内容System.out.println(str);}
}

回到顶部


Java实现生成和解析二维码相关推荐

  1. java生成以及解析二维码

    java生成以及解析二维码 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题,有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 ...

  2. Java生成和解析二维码工具类(简单经典)

    Java生成和解析二维码工具类 开箱即用,简单不废话. pom.xml引入依赖 <!-- https://mvnrepository.com/artifact/com.google.zxing/ ...

  3. java利用zxing来生成和解析二维码,支持中文

    java在二维码的生成和解析上,网上有些人说如果要解析中文,得去修改工具包的Encoder类中的 static final String DEFAULT_BYTE_MODE_ENCODING = &q ...

  4. 使用zxing生成与解析二维码

    随着二维码的普及,二维码在生活中的使用使用的场景也越来越来多,本文章就来介绍使用zxing来生成与解析二维码.生成二维码的开源项目很多,选择zxing则是因为其出自Google并且长期有人进行维护,值 ...

  5. java后台生成并下载二维码

    java后台生成并下载二维码(以二进制流的形式输出) 前提业务要求:前台页面展示数据,有下载按钮,点击下载,下载对应数据的二维码. 在pom.xml文件中添加依赖 <dependency> ...

  6. Java生成和解析二维码

    前言:曾经有做过不少微信公众号和移动网站的项目,对二维码还算有点了解,刚收到这个任务的时候就想着竟然要用二维码存文本,那就得先考究一下这小小的二维码到底能存多少的东西了. 需求:使用二维码存放文本(x ...

  7. java生成和解析二维码实战——QRCode

    直接上代码,以下程序可直接运行: package qrcode;import java.awt.Color; import java.awt.Graphics2D; import java.awt.i ...

  8. Java生成与解析二维码

    1.下载支持二维码的jar包qrcode.jar和qrcode_swetake.jar, 其中qrcode_swetake.jar用于生成二维码,rcode.jar用于解析二维码,jar包下载地址(免 ...

  9. java生成与解析二维码 支持插入图片与文字

    1.依赖: <!-- https://mvnrepository.com/artifact/com.google.zxing/core --><dependency><g ...

最新文章

  1. CentOS6.x配置tomcat搭建JSP应用服务器
  2. 编程珠玑第三章习题答案
  3. tf.reverse_sequence
  4. JZOJ 5393. 【NOIP2017提高A组模拟10.5】Snake vs Block
  5. python画图中grid等于true_Python中的matplotlib画图总结
  6. .NET程序员走向高端必读书单汇总
  7. 服务器性能指标(一)——负载(Load)分析及问题排查
  8. VS2005 VS2008新建网站和新建项目里选Web应用程序区别
  9. NOIP模拟题——神秘大门
  10. python生成list的时候 可以用lamda也可以不用_python 可迭代对象,迭代器和生成器,lambda表达式...
  11. 17 PP配置-生产计划-总体维护工厂参数
  12. classic example2
  13. C#:xml操作(待补充)
  14. mysql表结构及索引脚本
  15. 婚纱租赁APP开发功能模块解析
  16. 解决Windows Update错误“80072EFD”
  17. 零点城市社交电商2.1.7.4 VUE全端+全开源+全插件+独立版
  18. 大数据平台之今日头条采集,今日特卖全自动发布,淘宝达人有好货一键上传
  19. 免费送 2800套精品小程序源码!
  20. NaN表示什么?typeof NaN结果是什么?

热门文章

  1. MATLAB APP设计
  2. 解决办法在idea中搭建spark环境:Unable to fetch table student. Invalid method name: ‘get_table_req‘;
  3. 计算机视觉基础理论知识
  4. 基于jupyter notebook的简单爬虫学习记录
  5. 变量的生存期与存储类型
  6. 32岁,我从公司离职了,是裸辞......
  7. 域服务器用户一直被锁,Windows Server 2019 域用户账户锁定策略
  8. 四均线交易系统(Four Set of MA Crossover System)
  9. gulp4.0的坑:提示: Error: watching index.html: watch task has to be a function (optionally generated by u
  10. js生成html转换成图片保存,js将html生成为图片,并保存在本地