1.依赖

    <!--二维码--><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>

2.BufferedImageLuminanceSource类

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import com.google.zxing.LuminanceSource;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;}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;}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;}public boolean isCropSupported() {return true;}public LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);}public boolean isRotateSupported() {return true;}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);}}

3.QRCodeUtil类

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;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));}}

4.使用

public class QrCodeTest {public static void main(String[] args) throws Exception {// 存放在二维码中的内容String text = "二维码的内容";// 嵌入二维码的图片路径 null表示不在二维码中插入自己的图片String imgPath = null;// 生成的二维码的路径及名称String destPath = "E:/xx.jpg";//生成二维码QRCodeUtil.encode(text, imgPath, destPath, true);// 解析二维码String str = QRCodeUtil.decode(destPath);// 打印出解析出的内容System.out.println(str);}
}

5.在JavaWeb中使用

5.1 生成二维码

 //生成二维码private void makeQrCode(HttpServletRequest request, HttpServletResponse response) {// ..... 业务逻辑//可配置扫码后跳转的页面String text = "http://localhost:8081/#/verify/success";// 生成的二维码的路径及名称String destPath = "E:/xxx.jpg";//生成二维码QRCodeUtil.encode(text, null, destPath, true);// ..... 向前端响应成功与失败信息}

5.2 展示验证码到页面

 //获得二维码private void getVerify(HttpServletRequest request, HttpServletResponse response) {// ..... 处理验证的业务逻辑try {String filePath = "E:/xxx.jpg";FileInputStream fis = new FileInputStream(filePath);//创建一个输出流到浏览器response.setContentType("image/png");ServletOutputStream out = response.getOutputStream();int length = 0;byte[] buffer = new byte[1024];while ((length = fis.read(buffer)) != -1){out.write(buffer);}fis.close();} catch (Exception e) {e.printStackTrace();}}

5.3 前端

<img :src="verifyImg" />
-----------------------------------------------------------data() {return {verifyImg: '',}},
-----------------------------------------------------------
createQrCode() {let data = {//...你需要携带的数据}makeQrCode(data).then((res) => {//当生成验证成功后,请求获取验证码的图片axios.get('http://localhost:8080/equip/getVerify', {params: {// .... 需要携带的参数},responseType: 'arraybuffer',}).then((response) => {return ('data:image/png;base64,' +btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte),'')))}).then((data) => {//保存图片this.verifyImg = data})})},
export function makeQrCode(data) {return request({url: 'http://localhost:8080/xxx/makeQrCode',method: 'post',data,})
}

java生成二维码以及二维码的解码相关推荐

  1. JAVA 生成数据表图标LOGO二维码

    JAVA 生成数据表图标LOGO二维码 private static final int QRCOLOR = 0xFF000000; // 默认是黑色private static final int ...

  2. iText5实现Java生成PDF文件完整版,二维码

    iText5实现Java生成PDF文件完整版 vue 项目中分别使用 vue-pdf 插件和内嵌 iframe 实现 PDF 文件预览,缩放,旋转,下载,保存等功能 ? Vue打印文件(v-print ...

  3. java生成、识别条形码和二维码

    一.概述 使用 zxing 开源库 Zxing主要是Google出品的,用于识别一维码和二维码的第三方库 主要类: BitMatrix 位图矩阵 MultiFormatWriter 位图编写器 Mat ...

  4. java生成条码图片、打印二维码、图片合并、图片加文字

    通过java生成二维码图片,可以添加文字内容,非常方便实现打印. import java.awt.Color; import java.awt.Font; import java.awt.FontMe ...

  5. Java生成四种格式的二维码

    2022年2月23日 随着技术的不断发展与更新,现在的二维码的生成,完全可以交给前端来进行实现. 基于谷歌zxing实现的生成二维码工具类.可生成纯二维码:带Logo二维码:带文字二维码:带Logo带 ...

  6. java 生成带网络头像的二维码

    最近做一个带微信头像的二维码的功能,微信头像是一个链接,所以先把微信头像下载,临时保存,生成二维码 /*** 文件下载工具类** @author zhengxinghua*/ public class ...

  7. java生成SSCC编码第18位校验码

    问题描述 java实现SSCC编码校验位 public String add18EAN(String value) {if (value.length() < 17) {return value ...

  8. Java生成随机邀请码

    Java生成随机10位不重复邀请码 public static void main(String[] args) {for (int i = 0; i < 10; i++) {System.ou ...

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

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

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

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

最新文章

  1. Java NIO 学习笔记 缓冲区补充
  2. 获取Matlab 30天在线试用版本
  3. ACM中java的使用 (转)
  4. 企业架构(五)——联邦企业架构(FEA)实施指南
  5. 数列分块入门(套题)(loj6277,loj6278,loj6279,loj6280,loj6281,loj6282,loj6283,loj6284,loj6285)
  6. java swing 总结_java实验之swing图形用户界面程序设计及总结
  7. Apache Camel 2.21发布–新增功能
  8. Windows API 第二篇 SHGetSpecialFolderPath
  9. SublimeNFFT:Sublime Text 2从模板新建文件的插件
  10. hive 导出json格式 文件_Magicodes.IE在.NET Core中通过请求头导出多种格式文件
  11. 小女出世,暂停工作,全职照料大人小孩
  12. 随手记_C++语法中的一些注意事项
  13. ERA5再分析资料下载
  14. 用“法外狂徒”理解C++中的引用
  15. Shell获取配置文件中一个字段的值
  16. Web3.0入口-MPC钱包和智能合约钱包
  17. Java --- JVM动态链接与方法调用
  18. python古诗默写_Python网络爬虫:爬取古诗文中的某个制定诗句来实现搜索
  19. 英特尔采用 LLVM 作为最新 C/C++ 编译器
  20. 深夜爬虫, 我很抱歉 , 附微信 “ 网抑云” 公众号爬虫教程!

热门文章

  1. 好用的Mac笔记软件有哪些?
  2. S3C2440中时钟配置的那些事儿
  3. 阿里云服务器漏洞修复
  4. javascript利用回调函数解决异步困扰
  5. USB模块分析(四)- 设备列表权限申请
  6. speedoffice表格如何自动调整行高列宽?
  7. wireless-ac 9462驱动下载_英特尔官方更新 Win10 Wi-Fi 和蓝牙驱动程序
  8. 三菱5uplc伺服电机指令_2020北京三菱PLCFX3U128MT回收回收高价回收西克slck
  9. 吃苹果小游戏(Python)
  10. 他趣产品总监张俊杰:从“爹爹框架”看内容平台运营的 4 大关键点