![d4a9ee7980351f2dc248e6d6caae023c.png](https://i-blog.csdnimg.cn/blog_migrate/7f5aa41eb18c7ec66377f7bf48ab51be.jpeg)
![efdd171a49b7d528953188f9ed277a80.png](https://i-blog.csdnimg.cn/blog_migrate/18a11bd341800c274b2e68053d63a24e.png)
步骤1
第一步首先创建一个普通的 Maven 项目,然后要实现二维码功能,我们肯定要使用别人提供好的 Jar 包,这里我用的是 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>
步骤2
然后使用 google 提供的工具类,在项目根目录下创建一个 util 包,将所需要的工具类放进去。
![a9cc5a661d105a3602cc8116b3d6c771.png](https://i-blog.csdnimg.cn/blog_migrate/ab05fd3526aa5bf96c8545bdffe595c0.jpeg)
工具类1 (BufferedImageLuminanceSource)
不废话,直接上代码
/**
* @author bai <br/>
* @date 2020/7/1 9:27<br/>
*/
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;
}
@Override
public 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;
}
@Override
public 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;
}
@Override
public boolean isCropSupported() {
return true;
}
@Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
}
@Override
public boolean isRotateSupported() {
return true;
}
@Override
public 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)
这里面可以修改一些参数,例如二维码的尺寸,宽高等等。
/**
* @author bai <br/>
* @date 2020/7/1 9:29<br/>
*/
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) { // 压缩LOGO
if (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;
}
// 插入LOGO
Graphics2D 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 这种图片,将需要嵌入二维码的图片路径准备好就没有问题。
/**
* @author bai <br/>
* @date 2020/7/1 9:31<br/>
*/
public class QRCodeApplication {
public static void main(String[] args) throws Exception {
// 存放在二维码中的内容
// 二维码中的内容可以是文字,可以是链接等
String text = "http://www.baidu.com";
// 嵌入二维码的图片路径
//String imgPath = "C:UsersAdministratorPicturesimgdog.jpg";
// 生成的二维码的路径及名称
String destPath = "C:UsersbaiPicturesimgcode" + System.currentTimeMillis() + ".jpg";
//生成二维码
QRCodeUtil.encode(text, null, destPath, true);
// 解析二维码
String str = QRCodeUtil.decode(destPath);
// 打印出解析出的内容
System.out.println(str);
}
}
效果截图
![42cdbc432cba5338d38d763fba20dad8.png](https://i-blog.csdnimg.cn/blog_migrate/853b2022a71f262b797b45b44f445709.jpeg)
小编为大家准备的教程(免费)每天拿出2-3个小时自学就可以,学的时间长了,也一下子消化不了,如果你想学习的话,不如就从现在开始学习编程语言吧!
私信小编“学习”即可免费领取
![17b4a2ba7e38bb7296f4a757dbe96002.png](https://i-blog.csdnimg.cn/blog_migrate/922a46876ec88b15190907e6f897cfa6.png)
第一阶段 :Java基础
![b224547935fe7ca2ec4e985a298bc918.png](https://i-blog.csdnimg.cn/blog_migrate/68ed9f5ec5c0bf7a7cb55fb3bd6eda25.png)
1.认知基础课程2. java入门阶段3. 面向对象编程4. 飞机小项目5. 面向对象和数组6. 常用类7. 异常机制8. 容器和数据结构9. IO流技术10. 多线程11. 网络编程12. 手写服务器13. 注解和反射14. GOF23种设计模式15. 正则表达式16. JDBC数据库操作17. 手写SORM框架18. JAVA10新特性19.数据结构和算法20. JVM虚拟机讲解21. XML技术解析
第二阶段:数据库开发全套课程
![1c8f020d093f6a97b9e0931c76c1ac55.png](https://i-blog.csdnimg.cn/blog_migrate/fafa07f9186532077798502ed090192c.jpeg)
1.Oracle和SQL语言2.Mysql快速使用3.PowerDesigner使用4.JDBC数据库5.Mysql优化6.oracle深度讲解
第三阶段:网页开发和设计
![2bf4b5183b7a3cb28e1d7992c358ef47.png](https://i-blog.csdnimg.cn/blog_migrate/0015d7dff1f41459061e17fb9146d1fd.jpeg)
1.HTML基础2.CSS基础3.JavaScript编程4.jQuery5.easyUI
第四阶段:Servlet和JSP实战深入课程
![f18fdc50ddaa4f0c22c7541b9b36c04d.png](https://i-blog.csdnimg.cn/blog_migrate/7b4768785d121ddf3a872d3e65f0c3ac.jpeg)
1.Servlet入门和Tomcat2.request和response对象3.转发和重定向_Cookie4.session_Context对象5.JSP6.用户管理系统7.Ajax技术8.EL和JSTL标签库9.过滤器10.监听器
第五阶段:高级框架阶段
![8c557b5640939d450dd89808ad02ae7f.png](https://i-blog.csdnimg.cn/blog_migrate/710433f5029ad4941981de28dc53ae3d.png)
1.Mybatis2.Spring3.Spring MVC4.SSM框架整合5.RBAC权限控制项目6.Hibernate37.Hibernate48.jFinal9.Shiro安全框架10.Solr搜索框架11.Struts212.Nginx服务器13.Redis缓存技术14.JVM虚拟机优化15.Zookeeper
第六阶段:微服务架构阶段
![a7da7629a5774d4b0f5ef44f8e89b59e.png](https://i-blog.csdnimg.cn/blog_migrate/a69652b93ea71b7eaa104b093a9aa7d2.jpeg)
1.Spring Boot2.Spring Data3.Spring Cloud
第七阶段:互联网架构阶段
![97df9fc599e32cd2329dcf6e0475262c.png](https://i-blog.csdnimg.cn/blog_migrate/7d7c07278874c6ea5d513c8ff3789ad9.png)
1.Linux系统2.Maven技术3.Git4.SVN5.高并发编程6.系统和虚拟机调优7.JAVA编程规范8.高级网络编程9.Netty框架10.ActiveMQ消息中间件11.单点登录SSO12.数据库和SQL优化13.数据库集群和高并发14.Dubbo15.Redis16.VSFTPD+NGINX
第八阶段:分布式亿级高并发电商项目
![83fe8d08da505fd2f6b377d41a129c2e.png](https://i-blog.csdnimg.cn/blog_migrate/2dfd02fc2075f8ddd4a0945a10dc6ef7.png)
1.基于SOA架构介绍2.VSFTPD和Nginx和商品新增3.商品规格参数管理4.Jsonp5.CMS模块6.广告位数据缓存7.SolrJ和SolrCloud8.商品搜索9.商品详情10.单点登录11.购物车12.订单系统13.分库和分表14.分布式部署
第九阶段:毕设项目第一季
![4d2e67c37d492637bb9f0529748ac83c.png](https://i-blog.csdnimg.cn/blog_migrate/68b63e49f3bce16f61f0c63d2e727821.png)
1. 电子政务网2. 企业合同管理系统3. 健康管理系统4. 商品供应管理系统5. 土地档案管理系统6. 聊天室设计和实现7. 码头配套和货柜管理系统8. 百货中心供应链系统9. 病历管理系统10. 超市积分管理系统11. 动漫论坛12. 俄罗斯方块13. 个人博客系统14. 固定资产管理系统15. 影视创作论坛16. 屏幕截图工具17. 超级玛丽游戏18. 飞机大战游戏19. 雷电
第十阶段:毕设项目第二季
![39a6f6eea3f72db2fe9f76eb13add648.png](https://i-blog.csdnimg.cn/blog_migrate/ced2476f9deffb04d94a9e4f22012540.png)
1. 微博系统2. 写字板3. 坦克大战4. 推箱子5. 电脑彩票系统6. 记账管理系统7. 新闻发布系统8. 医院挂号系统9. 仓库管理系统10. 停车场管理系统11. 网络爬虫12. 酒店管理系统13. 企业财务管理系统14. 车辆管理系统15. 员工信息管理系统16. 旅游网站17. 搜索引擎18. 进销存管理系统19. 在线考试系统20. 物流信息网21. 住院管理系统22. 银行柜员业务绩效系统
获取方式:私信小编 “ 学习 ”,即可免费获取!
![463c62b8d5d2c2a04f4cb71e11e24955.png](https://i-blog.csdnimg.cn/blog_migrate/f89044c328f184be3f3395df4894430d.png)