目录

  • 1、POM
  • 2、普通二维码生成
  • 3、Logo二维码生成
  • 4、二维码解析
  • 5、完整代码

1、POM

        <dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.5.0</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.5.0</version></dependency>

2、普通二维码生成

工具类:

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;/*** 二维码生成工具类*/
public class QrCodeUtils {/*** 二维码尺寸*/private static final int QRCODE_SIZE = 300;/*** 生成二维码** @param url 二维码解析后的URL地址* @return 图片* @throws Exception*/public static BufferedImage getQrLogoCode(String url) throws Exception {Map<EncodeHintType, Object> hints = new HashMap<>(8);hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(url, 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);}}return image;}
}

实现类:

@RestController
@RequestMapping("/test")
@Slf4j
public class Controller {/*** 生成二维码** @param response*/@GetMapping(value = "/qr")public void getQrCodeImage(HttpServletResponse response) {try (OutputStream os = response.getOutputStream()) {String url = "https://www.baidu.com";// 生成二维码对象BufferedImage image = QrCodeUtils.getQrLogoCode(url);//设置responseresponse.setContentType("image/png");// 输出jpg格式图片ImageIO.write(image, "jpg", os);} catch (Exception e) {e.printStackTrace();throw new RuntimeException("二维码生成失败!");}}
}

测试:
地址:http://localhost:10010/test/qr

3、Logo二维码生成

工具类:

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
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.IOException;
import java.util.HashMap;
import java.util.Map;/*** 二维码生成工具类*/
public class QrCodeUtils {/*** 二维码尺寸*/private static final int QRCODE_SIZE = 300;/*** LOGO宽度*/private static final int LOGO_WIDTH = 80;/*** LOGO高度*/private static final int LOGO_HEIGHT = 80;/*** 生成二维码** @param url      二维码解析后的URL地址* @param logoPath logo地址 如果为空则表示不带logo* @return 图片* @throws Exception*/public static BufferedImage getQrLogoCode(String url, String logoPath) throws Exception {Map<EncodeHintType, Object> hints = new HashMap<>(8);hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(url, 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 (logoPath == null || "".equals(logoPath)) {return image;}// 插入图片QrCodeUtils.setLogoImage(image, logoPath);return image;}/*** 插入LOGO** @param source   二维码图片* @param logoPath LOGO图片地址* @throws IOException*/private static void setLogoImage(BufferedImage source, String logoPath) throws Exception {Image imageIo = ImageIO.read(new File(logoPath));int width = imageIo.getWidth(null);int height = imageIo.getHeight(null);// 设置图片尺寸,如果超过指定大小,则进行响应的缩小if (width > LOGO_WIDTH || height > LOGO_HEIGHT) {width = LOGO_WIDTH;height = LOGO_HEIGHT;}Image image = imageIo.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();// 重新绘制Image对象g.drawImage(image, 0, 0, null);g.dispose();imageIo = image;// 插入LOGOGraphics2D graph = source.createGraphics();// 设置为居中int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(imageIo, 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();}
}

实现类:

@RestController
@RequestMapping("/test")
@Slf4j
public class Controller {/*** 生成带logo的二维码** @param response*/@GetMapping(value = "/qr/logo")public void getQrLogoCodeImage(HttpServletResponse response) {try (OutputStream os = response.getOutputStream()) {String url = "https://www.baidu.com";String logoPath = "C:\\Users\\Desktop\\123.jpg";// 生成二维码对象BufferedImage image = QrCodeUtils.getQrLogoCode(url, logoPath);//设置responseresponse.setContentType("image/png");// 输出jpg格式图片ImageIO.write(image, "jpg", os);} catch (Exception e) {e.printStackTrace();throw new RuntimeException("二维码生成失败!");}}
}

测试:
地址:http://localhost:10010/test/qr

4、二维码解析

工具类:

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;/*** 二维码生成工具类*/
public class QrCodeUtils {/*** 解析二维码** @param inputStream 二维码图片流* @return* @throws Exception*/public static String decodeQrImage(InputStream inputStream) throws Exception {BufferedImage image = ImageIO.read(inputStream);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Map<DecodeHintType, Object> hints = new HashMap<>(2);hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");Result result = new MultiFormatReader().decode(bitmap, hints);return result.getText();}
}

实现类:

@RestController
@RequestMapping("/test")
@Slf4j
public class Controller {/*** 解析二维码图片,返回字符串** @param file*/@PostMapping(value = "/decode")public String decodeQrImage(@RequestParam("file") MultipartFile file) {try {InputStream inputStream = file.getInputStream();return QrCodeUtils.decodeQrImage(inputStream);} catch (Exception e) {e.printStackTrace();throw new RuntimeException("二维码解析失败!");}}
}

测试:
使用PostMan进行测试,将生成的二维码上传,可以看到成功返回了url数据

5、完整代码

工具类:

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
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.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;/*** 二维码生成工具类*/
public class QrCodeUtils {/*** 二维码尺寸*/private static final int QRCODE_SIZE = 300;/*** LOGO宽度*/private static final int LOGO_WIDTH = 80;/*** LOGO高度*/private static final int LOGO_HEIGHT = 80;/*** 生成二维码** @param url      二维码解析后的URL地址* @param logoPath logo地址 如果为空则表示不带logo* @return 图片* @throws Exception*/public static BufferedImage getQrLogoCode(String url, String logoPath) throws Exception {Map<EncodeHintType, Object> hints = new HashMap<>(8);hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(url, 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 (logoPath == null || "".equals(logoPath)) {return image;}// 插入图片QrCodeUtils.setLogoImage(image, logoPath);return image;}/*** 插入LOGO** @param source   二维码图片* @param logoPath LOGO图片地址* @throws IOException*/private static void setLogoImage(BufferedImage source, String logoPath) throws Exception {Image imageIo = ImageIO.read(new File(logoPath));int width = imageIo.getWidth(null);int height = imageIo.getHeight(null);// 设置图片尺寸,如果超过指定大小,则进行响应的缩小if (width > LOGO_WIDTH || height > LOGO_HEIGHT) {width = LOGO_WIDTH;height = LOGO_HEIGHT;}Image image = imageIo.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();// 重新绘制Image对象g.drawImage(image, 0, 0, null);g.dispose();imageIo = image;// 插入LOGOGraphics2D graph = source.createGraphics();// 设置为居中int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(imageIo, 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();}/*** 解析二维码** @param inputStream 二维码图片流* @return* @throws Exception*/public static String decodeQrImage(InputStream inputStream) throws Exception {BufferedImage image = ImageIO.read(inputStream);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Map<DecodeHintType, Object> hints = new HashMap<>(2);hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");Result result = new MultiFormatReader().decode(bitmap, hints);return result.getText();}
}

实现类:

@RestController
@RequestMapping("/test")
@Slf4j
public class Controller {/*** 生成二维码** @param response*/@GetMapping(value = "/qr")public void getQrCodeImage(HttpServletResponse response) {try (OutputStream os = response.getOutputStream()) {String url = "https://www.baidu.com";// 生成二维码对象BufferedImage image = QrCodeUtils.getQrLogoCode(url, null);//设置responseresponse.setContentType("image/png");// 输出jpg格式图片ImageIO.write(image, "jpg", os);} catch (Exception e) {e.printStackTrace();throw new RuntimeException("二维码生成失败!");}}/*** 生成带logo的二维码** @param response*/@GetMapping(value = "/qr/logo")public void getQrLogoCodeImage(HttpServletResponse response) {try (OutputStream os = response.getOutputStream()) {String url = "https://www.baidu.com";String logoPath = "C:\\Users\\LiGezZ\\Desktop\\123.jpg";// 生成二维码对象BufferedImage image = QrCodeUtils.getQrLogoCode(url, logoPath);//设置responseresponse.setContentType("image/png");// 输出jpg格式图片ImageIO.write(image, "jpg", os);} catch (Exception e) {e.printStackTrace();throw new RuntimeException("二维码生成失败!");}}/*** 解析二维码图片,返回字符串** @param file*/@PostMapping(value = "/decode")public String decodeQrImage(@RequestParam("file") MultipartFile file) {try {InputStream inputStream = file.getInputStream();return QrCodeUtils.decodeQrImage(inputStream);} catch (Exception e) {e.printStackTrace();throw new RuntimeException("二维码解析失败!");}}
}

Java生成、解析二维码方案以及代码实现相关推荐

  1. Java生成解析二维码

    Java生成二维码 一.介绍 1. 理解二维码 黑点代表二进制中的1,白点代表二进制中的0,通过1和0的排列组合,在二维空间记录数据.通过图像输入设备,读取其中的内容. 2. 二维码分类 二维码有不同 ...

  2. 几行代码搞定java生成解析二维码功能

    最近公司要求扫描二维码和生成二维码的功能.而群里部分网友也提到了.我这里就写了一个demo,和大家分享.代码很简介,希望大家能够喜欢. 网友表示在网上搜索了很多,发现不是代码不全,就是jar不匹配. ...

  3. Java简单的生成/解析二维码(zxing qrcode)

    Hi I'm Shendi Java简单的生成/解析二维码(zxing qrcode) 在之前使用 qrcode.js 方式生成二维码,但在不同设备上难免会有一些兼容问题,于是改为后端(Java)生成 ...

  4. java生成文字二维码、url二维码

    java生成文字二维码.url二维码 pom: 1)生成文字二维码 java工具类: 2)url地址生成二维码 java工具类: pom: <dependency><groupId& ...

  5. JAVA生成的二维码以及给二维码添加背景图片

    JAVA生成的二维码以及给二维码添加背景图片** 1.页面只需一行代码即可(用ajax请求得不到响应,也可以用表单提交) window.location.href = "${ctx}/qrc ...

  6. java生成圆形二维码logo

    自定义生成二维码,可以根据自己的喜欢在二维码中添加图片.有些代码是参考网上某位大神的,如有相同之处,请给我留言,我加上您的名字或者不让参考发表,则可删除. jar提取地址: 链接: https://p ...

  7. Java生成PDF417二维码

    pdf417二维码,比较头疼,网上找老长时间的资料,最后翻出来了个Itext.jar,那么就简单的说说如何使用iText.jar生成pdf417二维码 1,老规矩下载jar文件,我的资源里有----- ...

  8. 你有没有使用java生成过二维码?(二)

    作者专注于Java.架构.Linux.小程序.爬虫.自动化等技术. 工作期间含泪整理出一些资料,微信搜索[程序员高手之路],回复 [java][黑客][爬虫][小程序][面试]等关键字免费获取资料.技 ...

  9. 你有没有使用java生成过二维码?(一)

    作者专注于Java.架构.Linux.小程序.爬虫.自动化等技术. 工作期间含泪整理出一些资料,微信搜索[程序员高手之路],回复 [java][黑客][爬虫][小程序][面试]等关键字免费获取资料.技 ...

  10. java生成微信二维码,带页面跳转功能

    2019独角兽企业重金招聘Python工程师标准>>> package QRCode;import java.awt.image.BufferedImage; import java ...

最新文章

  1. RHEL/CentOS 一些不错的第三方软件包仓库
  2. Openstack部署工具
  3. Windows 技术篇 - 电脑秒速关机设置方法,注册表修改3个缓冲等待时间
  4. python继承——封装
  5. 华为鸿蒙系统如何升级,首批正式版没有荣耀,华为鸿蒙系统首批升级名单曝光:这些机主可坐等推送了...
  6. 利用R语言的Boruta包进行特征选择
  7. 小米蓝牙左右互联_399元,真香!小米蓝牙耳机Air,同价位比有线体验还出色?...
  8. android查看cpu型号_笔记本电脑cpu处理器怎么看?
  9. AndroidStudio 集成海康威视 Android SDK,集成萤石Android SDK
  10. CISSP重点知识总结1
  11. 《控制论导论》读书:机构-黑箱
  12. 打造您的赚钱机器2.0视频-精华笔记-独家分享
  13. 手机应用使用情况监控统计APP
  14. ★「C++游戏」BattleOfPhantom:大乱斗游戏升级版
  15. ERROR security.UserGroupInformation: Priviledge...
  16. python 文字识别 准确率_关于OCR图片文本检测、推荐一个 基于深度学习的Python 库!...
  17. 【ASM】字节码操作 ClassWriter COMPUTE_FRAMES 的作用 与 visitMaxs 的关系
  18. distiller的另一个实例正忙于启动_PLC编程实例丨一步一步教你设计PLC控制电机转停反控制系统~...
  19. 【vue】vue实现用户长时间不操作,提示用户登录已过期重新登录
  20. springmvc执行过程源码分析

热门文章

  1. 三极管设计,理解饱和,线性区域和截止区
  2. 循环系统疾病病人的护理题库【2】
  3. Babelua 调试
  4. powerpc linux交叉编译器,搭建PowerPC交叉编译器 三
  5. 电脑蓝牙打电话-总结(篇外、虚拟声卡选型)
  6. 织梦dedecms全自动采集的方法
  7. 西电微原课设——矩阵式键盘数字密码锁设计
  8. 数据挖掘技术研究现状
  9. 推荐16个国外的源码下载网站
  10. DOS命令:color