一,zxing是什么?

1,zxing的用途

如果我们做二维码的生成和扫描,通常会用到zxing这个库,

ZXing是一个开源的,用Java实现的多种格式的1D/2D条码图像处理库。

zxing还可以实现使用手机的内置的摄像头完成条形码的扫描及解码

2,zxing官方项目地址:

https://github.com/zxing/zxing

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,演示项目的相关信息

1,项目地址

https://github.com/liuhongdi/qrcode

2, 项目功能说明:

生成二维码直接展示

生成二维码保存成图片

解析二维码图片中的文字信息

3,项目结构,如图:

三,配置文件说明

1,pom.xml

        <!--qrcode begin-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency> <dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
<!--qrcode end-->

导入zxing库供生成qrcode使用

四,java代码说明

1,QrCodeUtil.java

/**
* 二维码工具类
* by liuhongdi
*/
public class QrCodeUtil { //编码格式,采用utf-8
private static final String UNICODE = "utf-8";
//图片格式
private static final String FORMAT = "JPG";
//二维码宽度像素pixels数量
private static final int QRCODE_WIDTH = 300;
//二维码高度像素pixels数量
private static final int QRCODE_HEIGHT = 300;
//LOGO宽度像素pixels数量
private static final int LOGO_WIDTH = 100;
//LOGO高度像素pixels数量
private static final int LOGO_HEIGHT = 100; //生成二维码图片
//content 二维码内容
//logoPath logo图片地址
private static BufferedImage createImage(String content, String logoPath) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, UNICODE);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT,
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 (logoPath == null || "".equals(logoPath)) {
return image;
}
// 插入图片
QrCodeUtil.insertImage(image, logoPath);
return image;
} //在图片上插入LOGO
//source 二维码图片内容
//logoPath LOGO图片地址
private static void insertImage(BufferedImage source, String logoPath) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
throw new Exception("logo file not found.");
}
Image src = ImageIO.read(new File(logoPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (width > LOGO_WIDTH) {
width = LOGO_WIDTH;
}
if (height > LOGO_HEIGHT) {
height = LOGO_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;
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_WIDTH - width) / 2;
int y = (QRCODE_HEIGHT - 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的二维码图片,保存到指定的路径
// content 二维码内容
// logoPath logo图片地址
// destPath 生成图片的存储路径
public static String save(String content, String logoPath, String destPath) throws Exception {
BufferedImage image = QrCodeUtil.createImage(content, logoPath);
File file = new File(destPath);
String path = file.getAbsolutePath();
File filePath = new File(path);
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdirs();
}
String fileName = file.getName();
fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())
+ "." + FORMAT.toLowerCase();
System.out.println("destPath:"+destPath);
ImageIO.write(image, FORMAT, new File(destPath));
return fileName;
} //生成二维码图片,直接输出到OutputStream
public static void encode(String content, String logoPath, OutputStream output)
throws Exception {
BufferedImage image = QrCodeUtil.createImage(content, logoPath);
ImageIO.write(image, FORMAT, output);
} //解析二维码图片,得到包含的内容
public static String decode(String path) throws Exception {
File file = new File(path);
BufferedImage image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, UNICODE);
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
}

工具类,包含了生成二维码、保存二维码,展示二维码,解析二维码

2,HomeController.java

@RequestMapping("/home")
@Controller
public class HomeController {
//生成带logo的二维码到response
@RequestMapping("/qrcode")
public void qrcode(HttpServletRequest request, HttpServletResponse response) {
String requestUrl = "http://www.baidu.com";
try {
OutputStream os = response.getOutputStream();
QrCodeUtil.encode(requestUrl, "/data/springboot2/logo.jpg", os);
} catch (Exception e) {
e.printStackTrace();
}
} //生成不带logo的二维码到response
@RequestMapping("/qrnologo")
public void qrnologo(HttpServletRequest request, HttpServletResponse response) {
String requestUrl = "http://www.baidu.com";
try {
OutputStream os = response.getOutputStream();
QrCodeUtil.encode(requestUrl, null, os);
} catch (Exception e) {
e.printStackTrace();
}
} //把二维码保存成文件
@RequestMapping("/qrsave")
@ResponseBody
public String qrsave() {
String requestUrl = "http://www.baidu.com";
try {
QrCodeUtil.save(requestUrl, "/data/springboot2/logo.jpg", "/data/springboot2/qrcode2.jpg");
} catch (Exception e) {
e.printStackTrace();
}
return "文件已保存";
} //解析二维码中的文字
@RequestMapping("/qrtext")
@ResponseBody
public String qrtext() {
String url = "";
try {
url = QrCodeUtil.decode("/data/springboot2/qrcode2.jpg");
} catch (Exception e) {
e.printStackTrace();
}
return "解析到的url:"+url;
}
}

入口处包含了四个方法,接下来我们做测试

五,测试效果

1,生成不带logo的二维码,访问:

http://127.0.0.1:8080/home/qrnologo

效果:

2,生成带logo的二维码:访问

http://127.0.0.1:8080/home/qrcode

效果:

3,生成二维码保存成文件:访问:

http://127.0.0.1:8080/home/qrsave

代码中文件被保存成了:/data/springboot2/qrcode2.jpg

4,解析二维码中包含的文字信息:访问:

http://127.0.0.1:8080/home/qrtext

返回:

解析到的url:http://www.baidu.com

成功解析到了图片中包含的url地址

六,查看spring boot版本

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)

spring boot:用zxing生成二维码,支持logo(spring boot 2.3.2)的更多相关文章

  1. 使用jquery.qrcode生成二维码支持logo,和中文

    /* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <iz@onicos.co. ...

  2. (转)ZXing生成二维码和带logo的二维码,模仿微信生成二维码效果

    场景:移动支付需要对二维码的生成与部署有所了解,掌握目前主流的二维码生成技术. 1 ZXing 生成二维码 首先说下,QRCode是日本人开发的,ZXing是google开发,barcode4j也是老 ...

  3. zxing生成二维码设置边框颜色

    真是研究了很久很久,满满的泪啊 zxing生成二维码,默认是可以增加空白边框的,但是并没有可以设置边框颜色的属性. 其中增加空白边框的属性的一句话是: Map hints = new HashMap( ...

  4. java学习-zxing生成二维码矩阵的简单例子

    这个例子需要使用google的开源项目zxing的核心jar包 core-3.2.0.jar 可以百度搜索下载jar文件,也可使用maven添加依赖 <dependency> <gr ...

  5. 通过zxing生成二维码

    二维码现在随处可见,在日常的开发中,也会经常涉及到二维码的生成,特别是开发一些活动或者推广方面的功能时,二维码甚至成为必备功能点.本文介绍通过 google 的 zxing 包生成带 logo 的二维 ...

  6. 使用google zxing生成二维码图片

    生成二维码工具类: 1 import java.awt.geom.AffineTransform; 2 import java.awt.image.AffineTransformOp; 3 impor ...

  7. 使用jquery-qrcode在页面上生成二维码,支持中文

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. C#Qrcode生成二维码支持中文,带图片,带文字

    C#Qrcode生成二维码支持中文带图片的操作请看二楼的帖子,当然开始需要下载一下C#Qrcode的源码 下载地址 : http://www.codeproject.com/Articles/2057 ...

  9. C# 生成二维码(带Logo)

    C# 生成二维码(带Logo) 第一种方式 我们需要引用 ThoughtWorks.QRCode.dll  生成带logo二维码(framework4.0以上) 下载地址:https://pan.ba ...

随机推荐

  1. charles 入门配置(win10+vivoX20)(Charles一)

    charles的几个功能可以参考:https://www.cnblogs.com/mihoutao/p/10601171.html 首先是charles的下载 下载地址:https://www.cha ...

  2. Django+bootstrap启动登录模板页面(Django三)

    上次用Django启动了我的第一个页面 具体步骤参考:初步启动DjangoDjango启动第一个页面但是页面非常简陋,所以我从网上找了个模板,下载网址:免费下载模板,解压后内部文件如下: 效果图:下面 ...

  3. Robotframework自动化5-基础关键字介绍2

    一:时间 1.获取当前时间 Get time   2.获取当月时间    ${yyyy} ${mm} ${day} Get Time year,month,day${time} Catenate SE ...

  4. 关于px、pt、em、rem四个单位的解释

    写在前面 最近在群里突然看到一个问题,就是px pt em rem 三者的区别,这个问题看起来非常基础,也非常容易被忽略,however,面试会问到~,那我就解释一下 px px的英文是pixel,翻 ...

  5. (专题一)03 matlab变量及其操作

    给内存单元取名字就可以访问内存单元 变量的命名:变量名区分大小写 标准函数名以及命名方式必须用小写字母 matlab赋值语句有两种表达式 变量的管理       1.预定义变量  ans 是默认赋值变 ...

  6. php处理的图片无法进CDN缓存

    今天发现线上有个问题,线上一个图片域名,在前端已经加了CDN缓存,不落缓存,则用PHP动态实现图片缩放,但经PHP处理过的图片输出后,每次都要从后端读取,后端服务器压力瞬间增加,经分析,PHP中没有作 ...

  7. redis并发问题2

    转自https://mp.weixin.qq.com/s?__biz=MzI1NDQ3MjQxNA==&mid=2247485464&idx=1&sn=8d690fc6f878 ...

  8. golang defer 以及 函数栈和return

    defer 作为延迟函数存在,在函数执行结束时才会正式执行,一般用于资源释放等操作 参考一段代码https://mp.weixin.qq.com/s/yfH0CBnUBmH0oxfC2evKBA来分析 ...

  9. powershell中使用Get-FileHash计算文件的hash值

    今天在公司一台windows服务器上.需要对两个文件进行比对,笔者首先就想到了可以使用md5校验 但是公司服务器上又不可以随意安装软件,于是笔者想到了可以试试windows自带的powershell中 ...

  10. 一键生成数据库文档,堪称数据库界的Swagger,有点厉害

    最近部门订单业务调整,收拢其他业务线的下单入口,做个统一大订单平台.需要梳理各业务线的数据表,但每个业务线库都有近百张和订单相关的表,挨个表一个一个字段的弄脑瓜子嗡嗡的. 为了不重复 CV 操作,抱着 ...